diff --git a/.gitignore b/.gitignore index 1eb913008..21847b79f 100644 --- a/.gitignore +++ b/.gitignore @@ -163,4 +163,6 @@ seeds.csv histogram # Ignore compilator by qemu qemu_* -core \ No newline at end of file +core +#Generate in Dolphin +.directory \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index b623fab46..5e7bb92aa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,18 +1,11 @@ sudo: required -services: - - docker language: go -go: matrix: include: - os: linux dist: xenial - os: osx - osx_image: xcode8.3 before_install: - - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then - sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test && sudo apt-get update -qq; - fi - ./ci-scripts/install-travis-gcc.sh - eval "CC=gcc-6 && CXX=g++-6" env: @@ -22,7 +15,7 @@ env: - LIB_DIR: lib - CGO_ENABLED: 1 - VERSION_UPGRADE_TEST_WAIT_TIMEOUT: 60s - - PATH_DIR: "$GOPATH/src/github.com/skycoin/libskycoin/" + - PATH_DIR: "$GOPATH/src/github.com/fibercrypto/libskycoin/" install: # Install gox - go get github.com/gz-c/gox @@ -53,7 +46,7 @@ deploy: draft: true overwrite: true on: - repo: skycoin/libskycoin + repo: fibercrypto/libskycoin tags: true notifications: email: false diff --git a/CHANGELOG.md b/CHANGELOG.md index b7a67d091..a104a288f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ # Changelog + All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) @@ -7,17 +8,142 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## Unreleased ### Added + - Added swagger specification for `Skycoin REST API` to v0.27.0 +- Added `wallet.collection_wallet` +- Added datatype `CollectionWallet__Handle` +- Added datatype `MetaWallet__Handle` +- Added function `SKY_wallet_CollectionWallet_AddEntry` +- Added function `SKY_wallet_CollectionWallet_GetEntry` +- Added function `SKY_wallet_CollectionWallet_GetAddresses` +- Added function `SKY_wallet_CollectionWallet_GenerateAddresses` +- Added function `SKY_wallet_MetaWallet_IsEncrypted` +- Added function `SKY_wallet_MetaWallet_Label` +- Added function `SKY_wallet_MetaWallet_Filename` +- Added function `SKY_wallet_MetaWallet_Version` +- Added function `SKY_wallet_MetaWallet_Type` +- Added datatype `WalletSeedResponse__Handle` +- Added datatype `Distribution__Handle` +- Added datatype `SKY_params_Distribution_GetMaxCoinSupply` +- Added datatype `SKY_params_Distribution_SetMaxCoinSupply` +- Added datatype `SKY_params_Distribution_GetInitialUnlockedCount` +- Added datatype `SKY_params_Distribution_SetInitialUnlockedCount` +- Added datatype `SKY_params_Distribution_GetUnlockAddressRate` +- Added datatype `SKY_params_Distribution_SetUnlockAddressRate` +- Added datatype `SKY_params_Distribution_GetUnlockTimeInterval` +- Added datatype `SKY_params_Distribution_SetUnlockTimeInterval` +- Added datatype `SKY_params_Distribution_GetAddresses` +- Added datatype `SKY_params_Distribution_SetAddresses` +- Added datatype `SKY_params_Distribution_Validate` +- Added datatype `SKY_params_Distribution_AddressInitialBalance` +- Added datatype `SKY_params_Distribution_UnlockedAddresses` +- Added datatype `SKY_params_Distribution_LockedAddresses` +- Added datatype `SKY_params_Distribution_AddressesDecoded` +- Added datatype `SKY_params_Distribution_UnlockedAddressesDecoded` +- Added datatype `SKY_params_Distribution_LockedAddressesDecoded` +- Added datatype `SKY_params_Distribution_GetMainNetDistribution` +- Added function `SKY_cipher_Sig_String` +- Added function `SKY_cipher_Sig_Null` +- Added function `SKY_cipher_VerifySignatureRecoverPubKey` +- Added datatype `CreateWalletOptionsHandle` +- Added function `SKY_api_Client_CreateWallet` +- Added function `SKY_api_Client_InjectTransactionNoBroadcast` +- Added function `SKY_api_Client_InjectEncodedTransactionNoBroadcast` +- Added function `SKY_api_Client_RecoverWallet` +- Added datatype `CreateWalletOptions__Handle` +- Added datatype `WalletRecoverRequest__Handle` +- Added datatype `PublicKey__Handle` +- Added datatype `PrivateKey__Handle` +- Added datatype `Path` +- Added datatype `PathNode` +- Added function `SKY_bip32_PrivateKey_DeriveSubpath` +- Added function `SKY_bip32_PrivateKey_Publickey` +- Added function `SKY_bip32_PrivateKey_Fingerprint` +- Added function `SKY_bip32_PublicKey_Fingerprint` +- Added function `SKY_bip32_PrivateKey_Identifier` +- Added function `SKY_bip32_PublicKey_Identifier` +- Added function `SKY_bip32_PrivateKey_NewPrivateChildKey` +- Added function `SKY_bip32_PrivateKey_NewPublicChildKey` +- Added function `SKY_bip32_PrivateKey_Serialize` +- Added function `SKY_bip32_PublicKey_Serialize` +- Added function `SKY_bip32_PrivateKey_String` +- Added function `SKY_bip32_PublicKey_String` +- Added function `SKY_bip32_DeserializeEncodedPrivateKey` +- Added function `SKY_bip32_DeserializePrivateKey` +- Added function `SKY_bip32_DeserializeEncodedPublicKey` +- Added function `SKY_bip32_DeserializePublicKey` +- Added function `SKY_bip32_PathNode_Hardened` +- Added function `SKY_bip32_ParsePath` +- Added datatype `bip44_CoinType` +- Added function `SKY_bip44_NewCoin` +- Added datatype `Account__Handle` +- Added datatype `Coin__Handle` +- Added function `SKY_bip44_Coin_Account` +- Added function `SKY_bip44_Account_External` +- Added function `SKY_bip44_Account_Change` +- Added function `SKY_bip44_Account_String` +- Added function `SKY_bip44_Account_GetPrivateKey` +- Added function `SKY_bip32_PrivateKey_GetKey` +- Added function `SKY_bip32_PublicKey_GetKey` +- Added datatype `coin__HashPair` +- Added function `SKY_bip32_PrivateKey_GetDepth` +- Added function `SKY_bip32_PublicKey_GetDepth` +- Added function `SKY_bip32_PrivateKey_ChildNumber` +- Added function `SKY_bip32_PublicKey_ChildNumber` +- Added function `SKY_bip32_PrivateKey_GetChainCode` +- Added function `SKY_bip32_PublicKey_GetChainCode` +- Added function `SKY_testutil_MakePubKey` +- Added function `SKY_testutil_RandXPub` +- Added datatype `wallet__CryptoType` +- Added function `SKY_cli_GetWalletOutputsFromFile` +- Added function `SKY_cli_GetWalletOutputs` +- Added function `SKY_cli_GetBalanceOfAddresses` +- Added datatype `GetOutputser__Handle` +- Added functions `SKY_coin_DeserializeTransactionHex` + +### Removed + +- Removed function `SKY_wallet_Wallet_AddEntry` +- Removed function `SKY_wallet_Wallet_GetEntry` +- Removed function `SKY_wallet_Wallet_GetAddresses` +- Removed function `SKY_wallet_Wallet_GenerateAddresses` +- Removed function `SKY_wallet_Wallet_IsEncrypted` +- Removed function `SKY_wallet_Wallet_Label` +- Removed function `SKY_wallet_Wallet_File` +- Removed function `SKY_wallet_Wallet_Version` +- Removed function `SKY_wallet_Wallet_Type` +- Removed function `SKY_cli_Config_FullWalletPath` +- Removed function `SKY_api_Client_CreateUnencryptedWallet` +- Removed function `SKY_api_Client_CreateEncryptedWallet` +- Removed function `SKY_cli_GenerateWallet` +- Removed function `SKY_params_GetDistributionAddresses` +- Removed function `SKY_params_GetUnlockedDistributionAddresses` +- Removed function `SKY_params_GetLockedDistributionAddresses` +- Removed function `SKY_wallet_LoadReadableWallet` +- Removed function `SKY_wallet_ReadableWallet_Save` +- Removed function `SKY_wallet_ReadableWallet_Load` +- Removed function `SKY_wallet_ReadableWallet_Erase` +- Removed function `SKY_api_Handle_GetWalletMeta` +- Removed function `SKY_api_Handle_GetWalletEntriesCount` +- Removed function `SKY_api_Handle_WalletGetEntry` +- Removed function `SKY_api_Handle_WalletResponseGetCryptoType` ### Changed + - Update `lib/curl` to v0.27.0 +- Update submodule to `skycoin == 0.27.0` +- Change datatype `SKY_cli_AddPrivateKey` +- Change datatype `SKY_api_Client_WalletSeed` +- Rename function `SKY_wallet_Wallet_Lock` => `SKY_wallet_Lock` +- Rename function `SKY_wallet_Wallet_Unlock` => `SKY_wallet_Unlock` ## [0.26.0] - 2019-07-12 ### Added + - Added datatype `api__TransactionInput` - Added datatype `transaction__UxBalance` -- Added function `SKY_transaction_NewUxBalances`, +- Added function `SKY_transaction_NewUxBalances`, - Added function `SKY_transaction_DistributeCoinHoursProportional`, `SKY_transaction_DistributeSpendHours` - Added funcion `SKY_coin_VerifyInputSignatures` - Added funcion `SKY_coin_BlockHeader_SetTime` @@ -33,6 +159,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Update /metrics endpoint to add metrics from /health: unspent_outputs, unconfirmed_txns, time_since_last_block_seconds, open_connections, outgoing_connections, incoming_connections, start_at, uptime_seconds, last_block_seq. ### Changed + - Support for this changed functions in `skyapi`: - Add /api/v1/resendUnconfirmedTxns to the WALLET API set - In POST /api/v1/wallet/transaction, moved wallet parameters to the top level of the object @@ -40,6 +167,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Increase the detail of error messages for invalid seeds sent to POST /api/v2/wallet/seed/verify ### Removed + - Removed symbolic links from vendor - Removed function `SKY_webrpc_NewClient`, `SKY_webrpc_Client_CSRF`, `SKY_webrpc_Client_InjectTransaction`, `SKY_webrpc_Client_GetStatus`,`SKY_webrpc_Client_GetTransactionByID`, `SKY_webrpc_Client_GetAddressUxOuts`, `SKY_webrpc_Client_GetBlocksInRange`, `SKY_webrpc_Client_GetBlocksBySeq` and `SKY_webrpc_Client_GetLastBlocks`. - Removed datatype `wallet__UxBalance` @@ -57,7 +185,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - The unversioned REST API (the -enable-unversioned-api is removed, prefix your API requests with /api/v1 if they don't have an /api/vx prefix already). See https://github.com/skycoin/skycoin/blob/develop/src/api/README.md#migrating-from-the-unversioned-api - /api/v1/wallet/spend endpoint (use POST /api/v1/wallet/transaction followed by POST /api/v1/injectTransaction instead). See https://github.com/skycoin/skycoin/blob/develop/src/api/README.md#migrating-from--api-v1-spend - ## [0.25.1] - 2019-06-30 ### Added @@ -91,4 +218,3 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. - Add `coin`, `wallet`, `util/droplet` and `util/fee` methods as part of `libskycoin` C API - Add `util/droplet` and `util/fee` API's as part of `libskycoin` - Implement SWIG interfaces in order to generate client libraries for multiple programming languages - diff --git a/Makefile b/Makefile index 407547ad7..18613981a 100644 --- a/Makefile +++ b/Makefile @@ -129,8 +129,9 @@ build-libc-dbg: configure-build build-libc-static build-libc-shared test-libc: build-libc ## Run tests for libskycoin C client library echo "Compiling with $(CC) $(CC_VERSION) $(STDC_FLAG)" - $(CC) -o $(BIN_DIR)/test_libskycoin_shared $(LIB_DIR)/cgo/tests/*.c $(LIB_DIR)/cgo/tests/testutils/*.c -lskycoin $(LDLIBS) $(LDFLAGS) - $(CC) -o $(BIN_DIR)/test_libskycoin_static $(LIB_DIR)/cgo/tests/*.c $(LIB_DIR)/cgo/tests/testutils/*.c $(BUILDLIB_DIR)/libskycoin.a $(LDLIBS) $(LDFLAGS) + $(eval TESTS_SRC := $(shell ls $(LIB_DIR)/cgo/tests/*.c | grep -v test_main_hw.c)) + $(CC) -o $(BIN_DIR)/test_libskycoin_shared $(TESTS_SRC) $(LIB_DIR)/cgo/tests/testutils/*.c -lskycoin $(LDLIBS) $(LDFLAGS) + $(CC) -o $(BIN_DIR)/test_libskycoin_static $(TESTS_SRC) $(LIB_DIR)/cgo/tests/testutils/*.c $(BUILDLIB_DIR)/libskycoin.a $(LDLIBS) $(LDFLAGS) $(LDPATHVAR)="$(LDPATH):$(BUILD_DIR)/usr/lib:$(BUILDLIB_DIR)" $(BIN_DIR)/test_libskycoin_shared $(LDPATHVAR)="$(LDPATH):$(BUILD_DIR)/usr/lib" $(BIN_DIR)/test_libskycoin_static @@ -168,8 +169,8 @@ check: lint test-libc lint-libc test-skyapi ## Run tests and linters install-linters-Linux: ## Install linters on GNU/Linux sudo apt-get update - sudo apt-get install $(PKG_CLANG_FORMAT) - sudo apt-get install $(PKG_CLANG_LINTER) + sudo apt-get install $(PKG_CLANG_FORMAT) -y + sudo apt-get install $(PKG_CLANG_LINTER) -y install-linters-Darwin: ## Install linters on Mac OSX # brew install $(PKG_CLANG_FORMAT) @@ -209,7 +210,9 @@ install-deps-libc: install-deps-libc-$(UNAME_S) ## Install deps for libc install-deps-skyapi: install-deps-skyapi-$(UNAME_S) ## Install skyapi(libcurl based) library. -install-deps-libc-Linux: configure-build ## Install locally dependencies for testing libskycoin +install-deps-libc-Linux: configure-build check-0.12.0/src/.libs/libcheck.so ## Install locally dependencies for testing libskycoin + +check-0.12.0/src/.libs/libcheck.so: ## Install libcheck wget -c https://github.com/libcheck/check/releases/download/0.12.0/check-0.12.0.tar.gz tar -xzf check-0.12.0.tar.gz cd check-0.12.0 && ./configure --prefix=/usr --disable-static && make && sudo make install @@ -226,6 +229,7 @@ clean-libc: ## Clean files generated by libc rm -rfv $(BUILDLIB_DIR) rm -rfv bin rm -rfv qemu_test_libskycoin* + rm -rfv qemu_* rm -rfv include/libskycoin.h clean-skyapi: ## Clean files generated by skyapi @@ -235,7 +239,7 @@ clean-skyhwd: ## Clean files generated by skyhwd rm -rfv $(BUILDLIBSKYHWD_DIR) clean: clean-libc clean-skyapi clean-skyhwd ## Clean all files generated by libraries - + rm -rfv $(BUILD_DIR) format-libc: $(PKG_CLANG_FORMAT) -sort-includes -i -assume-filename=.clang-format lib/cgo/tests/*.c $(PKG_CLANG_FORMAT) -sort-includes -i -assume-filename=.clang-format include/*.h diff --git a/README.md b/README.md index 4e72c9291..d7d92da64 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # Skycoin C library -[![Build Status](https://travis-ci.com/skycoin/libskycoin.svg)](https://travis-ci.com/skycoin/libskycoin) +[![Build Status](https://travis-ci.com/fibercrypto/libskycoin.svg)](https://travis-ci.com/fibercrypto/libskycoin) Skycoin C library (a.k.a `libskycoin`) exports the Skycoin API to DApps using the C programming language. It is also the foundation to build client libraries for other programming languages. diff --git a/docker/images/deploy-arm/Dockerfile b/docker/images/deploy-arm/Dockerfile index 2749a118e..f1b7c3846 100644 --- a/docker/images/deploy-arm/Dockerfile +++ b/docker/images/deploy-arm/Dockerfile @@ -6,20 +6,19 @@ ARG PROJECT_USERNAME ARG PROJECT_REPONAME ARG SHA1 ARG VERSION -ADD . $GOPATH/src/github.com/skycoin/libskycoin/ +ADD . $GOPATH/src/github.com/fibercrypto/libskycoin/ RUN [ "cross-build-start" ] -RUN ls -oa $GOPATH/src/github.com/skycoin/libskycoin/ -RUN sh $GOPATH/src/github.com/skycoin/libskycoin/ci-scripts/docker_install_debian.sh -RUN make -C $GOPATH/src/github.com/skycoin/libskycoin dep +RUN sh $GOPATH/src/github.com/fibercrypto/libskycoin/ci-scripts/docker_install_debian.sh +RUN make -C $GOPATH/src/github.com/fibercrypto/libskycoin dep RUN go get github.com/gz-c/gox RUN go get -t ./... ENV CGO_ENABLED=1 ENV ARCH=${QEMU_PLATFORM} ENV OS="Linux" -RUN make -C $GOPATH/src/github.com/skycoin/libskycoin build -RUN tar -czf libskycoin-${VERSION}-${OS}-${ARCH}.tar.gz -C $GOPATH/src/github.com/skycoin/libskycoin/build $GOPATH/src/github.com/skycoin/libskycoin/build/* +RUN make -C $GOPATH/src/github.com/fibercrypto/libskycoin build +RUN tar -czf libskycoin-${VERSION}-${OS}-${ARCH}.tar.gz -C $GOPATH/src/github.com/fibercrypto/libskycoin/build $GOPATH/src/github.com/fibercrypto/libskycoin/build/* RUN go get github.com/tcnksm/ghr RUN ghr -t ${GITHUB_OAUTH_TOKEN} -u ${PROJECT_USERNAME} -r ${PROJECT_REPONAME} -c ${SHA1} -replace -draft ${VERSION} libskycoin-${VERSION}-${OS}-${ARCH}.tar.gz diff --git a/docker/images/test-arm/Dockerfile b/docker/images/test-arm/Dockerfile index 804a63730..80ef80e45 100644 --- a/docker/images/test-arm/Dockerfile +++ b/docker/images/test-arm/Dockerfile @@ -5,20 +5,20 @@ FROM balenalib/${QEMU_PLATFORM}-${QEMU_OS}-golang # See https://travis-ci.org/simelo/libskycoin/jobs/529481211#L649-L653 ARG QEMU_OS -ADD . $GOPATH/src/github.com/skycoin/libskycoin/ +ADD . $GOPATH/src/github.com/fibercrypto/libskycoin/ RUN [ "cross-build-start" ] -RUN ls -oa $GOPATH/src/github.com/skycoin/libskycoin/ -RUN sh $GOPATH/src/github.com/skycoin/libskycoin/ci-scripts/docker_install_${QEMU_OS}.sh -RUN make -C $GOPATH/src/github.com/skycoin/libskycoin dep +RUN ls -oa $GOPATH/src/github.com/fibercrypto/libskycoin/ +RUN sh $GOPATH/src/github.com/fibercrypto/libskycoin/ci-scripts/docker_install_${QEMU_OS}.sh +RUN make -C $GOPATH/src/github.com/fibercrypto/libskycoin dep RUN go get github.com/gz-c/gox RUN go get -t ./... ENV CGO_ENABLED=1 -RUN make -C $GOPATH/src/github.com/skycoin/libskycoin clean-libc -RUN make -C $GOPATH/src/github.com/skycoin/libskycoin test-libc +RUN make -C $GOPATH/src/github.com/fibercrypto/libskycoin clean-libc +RUN make -C $GOPATH/src/github.com/fibercrypto/libskycoin test-libc RUN [ "cross-build-end" ] -WORKDIR $GOPATH/src/github.com/skycoin +WORKDIR $GOPATH/src/github.com/fibercrypto VOLUME $GOPATH/src/ \ No newline at end of file diff --git a/include/cipher.bip32.path.go.h b/include/cipher.bip32.path.go.h new file mode 100644 index 000000000..9cad67835 --- /dev/null +++ b/include/cipher.bip32.path.go.h @@ -0,0 +1,9 @@ +typedef struct { + GoSlice_ Elements; // Goslice de bip32__PathNode +} bip32__Path; + +// PathNode is an element of an HD wallet path +typedef struct { + BOOL Master; + GoUint32_ ChildNumber; +} bip32__PathNode; \ No newline at end of file diff --git a/include/cipher.bip44.bip44.go.h b/include/cipher.bip44.bip44.go.h new file mode 100644 index 000000000..db69b62d6 --- /dev/null +++ b/include/cipher.bip44.bip44.go.h @@ -0,0 +1 @@ +typedef GoUint32_ bip44_CoinType; diff --git a/include/cli.cli.go.h b/include/cli.cli.go.h index de6f25912..c8b119586 100644 --- a/include/cli.cli.go.h +++ b/include/cli.cli.go.h @@ -1 +1,7 @@ -typedef GoSlice_ cli__PasswordFromBytes; +typedef struct { + void* data; ///< Pointer to buffer containing slice data. + GoInt_ len; ///< Number of items stored in slice buffer + GoInt_ cap; ///< Maximum number of items that fits in this slice + ///< considering allocated memory and item type's + ///< size. +} cli__PasswordFromBytes; diff --git a/include/coin.block.go.h b/include/coin.block.go.h index 370aa3306..9be17fe42 100644 --- a/include/coin.block.go.h +++ b/include/coin.block.go.h @@ -19,3 +19,8 @@ typedef struct { coin__Block _unnamed; cipher__Sig Sig; } coin__SignedBlock; + +typedef struct { + cipher__SHA256 Hash; + cipher__SHA256 PrevHash; +} coin__HashPair; diff --git a/include/coin.outputs.go.h b/include/coin.outputs.go.h index 271c49bc9..737c9731b 100644 --- a/include/coin.outputs.go.h +++ b/include/coin.outputs.go.h @@ -3,7 +3,6 @@ typedef struct { GoUint64_ BkSeq; } coin__UxHead; -typedef GoSlice_ coin__UxArray; typedef struct { cipher__SHA256 SrcTransaction; @@ -16,3 +15,9 @@ typedef struct { coin__UxHead Head; coin__UxBody Body; } coin__UxOut; + +typedef struct { + void* data; + GoInt_ len; + GoInt_ cap; +} coin__UxArray; \ No newline at end of file diff --git a/include/coin.transactions.go.h b/include/coin.transactions.go.h index fe56ff539..993a28907 100644 --- a/include/coin.transactions.go.h +++ b/include/coin.transactions.go.h @@ -1,4 +1,10 @@ -typedef GoSlice_ coin__Transactions; +typedef struct { + void* data; + GoInt_ len; + GoInt_ cap; + + +} coin__Transactions; /** * Skycoin transaction. * diff --git a/include/json.h b/include/json.h index d8534fc70..467aa3a51 100644 --- a/include/json.h +++ b/include/json.h @@ -166,7 +166,7 @@ typedef struct _json_value { #endif -/* Some C++ operator sugar */ + /* Some C++ operator sugar */ #ifdef __cplusplus diff --git a/include/skyassert.h b/include/skyassert.h index 74bcb69ae..4ee92d2b8 100644 --- a/include/skyassert.h +++ b/include/skyassert.h @@ -4,30 +4,47 @@ #include "libskycoin.h" #include "skyerrors.h" -extern GoInt_ isAddressEq(cipher__Address* addr1, cipher__Address* addr2); -extern GoInt_ isAddressEqPtr(cipher__Address addr1, cipher__Address addr2); +extern GoInt isAddressEq(cipher__Address* addr1, cipher__Address* addr2); -extern GoInt_ isBitcoinAddressEq(cipher__BitcoinAddress* addr1, cipher__BitcoinAddress* addr2); -extern GoInt_ isPubKeyEq(cipher__PubKey* pubkey1, cipher__PubKey* pubkey2); -extern GoInt_ isSigEq(cipher__Sig* sig1, cipher__Sig* sig2); +extern GoInt isAddressEqPtr(cipher__Address addr1, cipher__Address addr2); -extern GoInt_ isSecKeyEq(cipher__SecKey* seckey1, cipher__SecKey* seckey2); -extern GoInt_ isU8Eq(unsigned char p1[], unsigned char p2[], size_t len); +extern GoInt isBitcoinAddressEq(cipher__BitcoinAddress* addr1, cipher__BitcoinAddress* addr2); -extern GoInt_ isGoSliceEq(GoSlice* slice1, GoSlice* slice2); -extern GoInt_ isGoSlice_Eq(GoSlice_* slice1, GoSlice_* slice2); +extern GoInt isPubKeyEq(cipher__PubKey* pubkey1, cipher__PubKey* pubkey2); -extern GoInt_ isUxOutEq(coin__UxOut* x1, coin__UxOut* x2); +extern GoInt isSigEq(cipher__Sig* sig1, cipher__Sig* sig2); -extern GoInt_ isUxArrayEq(coin__UxArray* x1, coin__UxArray* x2); +extern GoInt isSecKeyEq(cipher__SecKey* seckey1, cipher__SecKey* seckey2); -extern GoInt_ isTransactionEq(coin__Transaction* x1, coin__Transaction* x2); +extern GoInt isSHA256Eq(cipher__SHA256* sh1, cipher__SHA256* sh2); -extern GoInt_ isTransactionsEq(coin__Transactions* x1, coin__Transactions* x2); +extern GoInt isRipemd160Eq(cipher__Ripemd160* rip1, cipher__Ripemd160* rip2); -extern GoInt_ isTransactionOutputEq(coin__TransactionOutput* x1, coin__TransactionOutput* x2); +extern GoInt isU8Eq(unsigned char p1[], unsigned char p2[], size_t len); -extern GoInt_ isGoStringEq(GoString string1, GoString string2); -extern GoInt_ isGoString_Eq(GoString_ string1, GoString_ string2); +extern GoInt isGoSliceEq(GoSlice* slice1, GoSlice* slice2); + +extern GoInt isGoSlice_Eq(GoSlice_* slice1, GoSlice_* slice2); + +extern GoInt isUxOutEq(coin__UxOut* x1, coin__UxOut* x2); + +extern GoInt isUxArrayEq(coin__UxArray* slice1, coin__UxArray* slice2); + +extern GoInt isTransactionEq(coin__Transaction* x1, coin__Transaction* x2); + +extern GoInt isTransactionHandleEq(Transaction__Handle* handle1, Transaction__Handle* handle2); + +extern GoInt isTransactionsEq(coin__Transactions* x1, coin__Transactions* x2); + +extern GoInt isTransactionOutputEq(coin__TransactionOutput* x1, coin__TransactionOutput* x2); + +extern GoInt isGoStringEq(GoString string1, GoString string2); + +extern GoInt isGoString_Eq(GoString_ string1, GoString_ string2); + +extern GoInt isGoString_toGoStringEq(GoString_ string1, GoString string2); + +extern GoInt isPrivateKeyEq(PrivateKey__Handle handle1, PrivateKey__Handle handle2); +extern GoInt isPublicKeyEq(PublicKey__Handle handle1, PublicKey__Handle handle2); #endif // LIBSKY_ASSERT_H diff --git a/include/skyerrors.h b/include/skyerrors.h index a6e7e2b1a..1addfee8f 100644 --- a/include/skyerrors.h +++ b/include/skyerrors.h @@ -95,6 +95,27 @@ #define SKY_ErrInvalidPassword 0x02000032 #define SKY_ErrReadDataLengthFailed 0x02000033 #define SKY_ErrInvalidDataLength 0x02000034 +#define SKY_ErrSerializedKeyWrongSize 0x02000035 +#define SKY_ErrHardenedChildPublicKey 0x02000036 +#define SKY_bip32_ErrInvalidChecksum 0x02000037 +#define SKY_ErrDerivedInvalidPrivateKey 0x02000038 +#define SKY_ErrDerivedInvalidPublicKey 0x02000039 +#define SKY_ErrInvalidPrivateKeyVersion 0x0200003A +#define SKY_ErrInvalidPublicKeyVersion 0x0200003B +#define SKY_ErrInvalidSeedLength 0x0200003C +#define SKY_ErrDeserializePrivateFromPublic 0x0200003D +#define SKY_ErrInvalidKeyVersion 0x0200003E +#define SKY_ErrInvalidFingerprint 0x0200003F +#define SKY_ErrInvalidChildNumber 0x02000040 +#define SKY_ErrInvalidPrivateKey 0x02000041 +#define SKY_ErrInvalidPublicKey 0x02000042 +#define SKY_ErrMaxDepthReached 0x02000043 +#define SKY_ErrInvalidCoinType 0x02000044 +#define SKY_ErrInvalidAccount 0x02000045 +#define SKY_ErrPathNoMaster 0x02000046 +#define SKY_ErrPathChildMaster 0x02000047 +#define SKY_ErrPathNodeNotNumber 0x02000048 +#define SKY_ErrPathNodeNumberTooLarge 0x02000049 // cli error codes #define SKY_ErrTemporaryInsufficientBalance 0x03000000 @@ -213,6 +234,7 @@ #define SKY_ErrVerifySignatureInvalidSigLength 0x0B000034 #define SKY_ErrVerifySignatureInvalidPubkeysLength 0x0B000035 + // daemon error codes #define SKY_ErrInvalidDecimals 0x0C000000 diff --git a/include/skytest.h b/include/skytest.h index 0e0bbbbd5..6375dd490 100644 --- a/include/skytest.h +++ b/include/skytest.h @@ -12,7 +12,7 @@ *---------------------------------------------------------------------- */ -void fprintbuff(FILE* f, void* buff, size_t n); +// void fprintbuff(FILE* f, void* buff, size_t n); /*---------------------------------------------------------------------- * Memory handling @@ -43,9 +43,12 @@ int copyGoSlice_toGoSlice(GoSlice* pdest, GoSlice_* psource, int elem_size); int copycoin_UxArraytoGoSlice(GoSlice* pdest, coin__UxArray* psource, int elem_size); int cutSlice(GoSlice_* slice, int start, int end, int elem_size, GoSlice_* result); +int cutUxArray(coin__UxArray* slice, int start, int end, int elem_size, coin__UxArray* result); int concatSlices(GoSlice_* slice1, GoSlice_* slice2, int elem_size, GoSlice_* result); +int concatUxArray(coin__UxArray* slice1, coin__UxArray* slice2, int elem_size, coin__UxArray* result); +int copyGoStringtoGoString_(GoString* pdest, GoString_* psource); /*---------------------------------------------------------------------- * JSON helpers *---------------------------------------------------------------------- diff --git a/include/skytxn.h b/include/skytxn.h index 001852bae..104e424b1 100644 --- a/include/skytxn.h +++ b/include/skytxn.h @@ -22,15 +22,15 @@ GoUint32_ makeUxOut(coin__UxOut* puxOut); GoUint32_ makeAddress(cipher__Address* paddress); -coin__Transaction* makeTransactionFromUxOut(coin__UxOut* puxOut, cipher__SecKey* pseckey, Transaction__Handle* handle); +void makeTransactionFromUxOut(coin__UxOut* puxOut, cipher__SecKey* pseckey, Transaction__Handle* handle); -coin__Transaction* makeTransaction(Transaction__Handle* handle); +void makeTransaction(Transaction__Handle* handle); -coin__Transaction* makeEmptyTransaction(Transaction__Handle* handle); +void makeEmptyTransaction(Transaction__Handle* handle); GoUint32_ makeTransactions(int n, Transactions__Handle* handle); -coin__Transaction* copyTransaction(Transaction__Handle handle, Transaction__Handle* handle2); +void copyTransaction(Transaction__Handle handle, Transaction__Handle* handle2); void makeRandHash(cipher__SHA256* phash); diff --git a/include/skytypes.gen.h b/include/skytypes.gen.h index 0123943c5..12002c4e7 100644 --- a/include/skytypes.gen.h +++ b/include/skytypes.gen.h @@ -26,7 +26,9 @@ #include "wallet.entry.go.h" #include "wallet.notes.go.h" #include "wallet.wallet.go.h" +#include "wallet.crypto.go.h" #include "transaction.choose.go.h" #include "api.send.go.h" +#include "cipher.bip32.path.go.h" \ No newline at end of file diff --git a/include/skytypes.h b/include/skytypes.h index f61c00352..aab8c82b2 100644 --- a/include/skytypes.h +++ b/include/skytypes.h @@ -114,6 +114,50 @@ typedef void* GoMap_; */ typedef void* GoChan_; +/** + * Instances of Go interface types. + */ +typedef struct { + void* t; ///< Pointer to the information of the concrete Go type + ///< bound to this interface reference. + void* v; ///< Pointer to the data corresponding to the value + ///< bound to this interface type. +} GoInterface_; +/** + * Instances of Go slices + */ +typedef struct { + void* data; + GoInt_ len; + GoInt_ cap; +} GoSlice_; + +typedef struct { + BOOL neg; + GoSlice_ nat; +} Number; + +typedef struct { + // TODO: stdevEclipse Define Signature + Number R; + Number S; +} Signature; + +#include "skytypes.gen.h" + +/** + * Internal representation of a Skycoin wallet. + */ +typedef struct { + GoMap_ Meta; ///< Records items that are not deterministic, like filename, + ///< lable, wallet type, secrets, etc. + GoSlice_ Entries; ///< Entries field stores the address entries that are + ///< deterministically generated from seed. +} Wallet; + +typedef GoUint8_ poly1305__Mac[16]; +typedef GoUint8_ poly1305__Key[32]; + /** * Memory handles returned back to the caller and manipulated * internally by API functions. Usually used to avoid type dependencies @@ -171,10 +215,6 @@ typedef Handle WalletResponse__Handle; */ typedef Handle CreateTransactionRequest__Handle; -/** - * String Slice Handle - */ -typedef Handle Strings__Handle; /** * Instances of Go `map` type, deal map[string] as handle @@ -196,51 +236,67 @@ typedef Handle ReadableOutputSet_Handle; */ typedef Handle CreateTransactionParams__Handle; + /** - * Instances of Go interface types. + * CollectionWallets Handle, slice of Wallet */ -typedef struct { - void* t; ///< Pointer to the information of the concrete Go type - ///< bound to this interface reference. - void* v; ///< Pointer to the data corresponding to the value - ///< bound to this interface type. -} GoInterface_; +typedef Handle CollectionWallet__Handle; + /** - * Instances of Go slices + * MetaWallet__Handle Handle, slice of Wallet */ -typedef struct { - void* data; ///< Pointer to buffer containing slice data. - GoInt_ len; ///< Number of items stored in slice buffer - GoInt_ cap; ///< Maximum number of items that fits in this slice - ///< considering allocated memory and item type's - ///< size. -} GoSlice_; +typedef Handle MetaWallet__Handle; -typedef struct { - BOOL neg; - GoSlice_ nat; -} Number; +/** + * MetaWallet__Handle Handle, slice of Wallet + */ +typedef Handle WalletSeedResponse__Handle; -typedef struct { - // TODO: stdevEclipse Define Signature - Number R; - Number S; -} Signature; +/** + * Distribution__Handle Handle, struct param.distribution + */ +typedef Handle Distribution__Handle; -#include "skytypes.gen.h" +/** + * CreateWalletOptions__Handle Handle, struct api.CreateWalletOptions + */ +typedef Handle CreateWalletOptions__Handle; /** - * Internal representation of a Skycoin wallet. + * WalletRecoverRequest__Handle Handle, struct api.WalletRecoverRequest */ -typedef struct { - GoMap_ Meta; ///< Records items that are not deterministic, like filename, - ///< lable, wallet type, secrets, etc. - GoSlice_ Entries; ///< Entries field stores the address entries that are - ///< deterministically generated from seed. -} Wallet; +typedef Handle WalletRecoverRequest__Handle; -typedef GoUint8_ poly1305__Mac[16]; -typedef GoUint8_ poly1305__Key[32]; +/** + * PublicKey__Handle Handle, struct bip32.Publickey + */ +typedef Handle PublicKey__Handle; + +/** + * PrivateKey__Handle Handle, struct bip32.Privatekey + */ +typedef Handle PrivateKey__Handle; + +/** + * Path__Handle Handle, struct bip32.Path + */ +typedef Handle Path__Handle; + +/** + * Coin__Handle Handle, struct bip44.Coin + */ +typedef Handle Coin__Handle; + +/** + * Account__Handle Handle, struct bip44.Account + */ +typedef Handle Account__Handle; + +/** + * GetOutputser__Handle Handle, interface cli.GetOutputser + */ + +typedef Handle GetOutputser__Handle; /** * Memory handle for internal object retrieving password to read @@ -339,7 +395,7 @@ typedef Handle TransactionResult_Handle; * Memory handle to access to coin.SortableTransactions */ -typedef Handle SortableTransactionResult_Handle; +typedef Handle SortableTransactions_Handle; /** * Memory handle to access to wallet.Notes diff --git a/include/visor.readable.go.h b/include/visor.readable.go.h index 55da60966..e69de29bb 100644 --- a/include/visor.readable.go.h +++ b/include/visor.readable.go.h @@ -1 +0,0 @@ -typedef GoSlice_ visor__ReadableOutputs; diff --git a/include/wallet.crypto.go.h b/include/wallet.crypto.go.h new file mode 100644 index 000000000..606e75981 --- /dev/null +++ b/include/wallet.crypto.go.h @@ -0,0 +1,6 @@ + +typedef struct { + const char* p; ///< Pointer to string characters buffer. + GoInt_ n; ///< String size not counting trailing `\0` char + ///< if at all included. +} wallet__CryptoType; \ No newline at end of file diff --git a/lib/cgo/api.client.go b/lib/cgo/api.client.go index 9777fc634..de58701ed 100644 --- a/lib/cgo/api.client.go +++ b/lib/cgo/api.client.go @@ -27,7 +27,7 @@ func SKY_api_NewClient(_addr string, _arg1 *C.Client__Handle) (____error_code ui } //export SKY_api_Client_CSRF -func SKY_api_Client_CSRF(_c C.Client__Handle, _arg0 *C.GoString_) (____error_code uint32) { +func SKY_api_Client_CSRF(_c C.Client__Handle, _arg0 *string) (____error_code uint32) { c, okc := lookupClientHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE @@ -36,7 +36,7 @@ func SKY_api_Client_CSRF(_c C.Client__Handle, _arg0 *C.GoString_) (____error_cod __arg0, ____return_err := c.CSRF() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg0, _arg0) + *_arg0 = __arg0 } return } @@ -290,45 +290,8 @@ func SKY_api_Client_Wallets(_c C.Client__Handle, _arg0 *C.Wallets__Handle) (____ return } -//export SKY_api_Client_CreateUnencryptedWallet -func SKY_api_Client_CreateUnencryptedWallet(_c C.Client__Handle, _seed, _label string, _scanN int, _arg2 *C.WalletResponse__Handle) (____error_code uint32) { - c, okc := lookupClientHandle(_c) - if !okc { - ____error_code = SKY_BAD_HANDLE - return - } - seed := _seed - label := _label - scanN := _scanN - __arg2, ____return_err := c.CreateUnencryptedWallet(seed, label, scanN) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - *_arg2 = registerWalletResponseHandle(__arg2) - } - return -} - -//export SKY_api_Client_CreateEncryptedWallet -func SKY_api_Client_CreateEncryptedWallet(_c C.Client__Handle, _seed, _label, _password string, _scanN int, _arg2 *C.WalletResponse__Handle) (____error_code uint32) { - c, okc := lookupClientHandle(_c) - if !okc { - ____error_code = SKY_BAD_HANDLE - return - } - seed := _seed - label := _label - password := _password - scanN := _scanN - __arg2, ____return_err := c.CreateEncryptedWallet(seed, label, password, scanN) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - *_arg2 = registerWalletResponseHandle(__arg2) - } - return -} - //export SKY_api_Client_NewWalletAddress -func SKY_api_Client_NewWalletAddress(_c C.Client__Handle, _id string, _n int, _password string, _arg3 *C.Strings__Handle) (____error_code uint32) { +func SKY_api_Client_NewWalletAddress(_c C.Client__Handle, _id string, _n int, _password string, _arg3 *[]string) (____error_code uint32) { c, okc := lookupClientHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE @@ -340,7 +303,7 @@ func SKY_api_Client_NewWalletAddress(_c C.Client__Handle, _id string, _n int, _p __arg3, ____return_err := c.NewWalletAddress(id, n, password) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - *_arg3 = (C.Strings__Handle)(registerHandle(__arg3)) + *_arg3 = __arg3 } return } @@ -413,7 +376,7 @@ func SKY_api_Client_WalletFolderName(_c C.Client__Handle, _arg0 *C.Handle) (____ } //export SKY_api_Client_NewSeed -func SKY_api_Client_NewSeed(_c C.Client__Handle, _entropy int, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_api_Client_NewSeed(_c C.Client__Handle, _entropy int, _arg1 *string) (____error_code uint32) { c, okc := lookupClientHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE @@ -423,13 +386,13 @@ func SKY_api_Client_NewSeed(_c C.Client__Handle, _entropy int, _arg1 *C.GoString __arg1, ____return_err := c.NewSeed(entropy) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg1, _arg1) + *_arg1 = __arg1 } return } //export SKY_api_Client_WalletSeed -func SKY_api_Client_WalletSeed(_c C.Client__Handle, _id string, _password string, _arg2 *C.GoString_) (____error_code uint32) { +func SKY_api_Client_WalletSeed(_c C.Client__Handle, _id string, _password string, _arg2 *C.WalletSeedResponse__Handle) (____error_code uint32) { c, okc := lookupClientHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE @@ -440,7 +403,7 @@ func SKY_api_Client_WalletSeed(_c C.Client__Handle, _id string, _password string __arg2, ____return_err := c.WalletSeed(id, password) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg2, _arg2) + *_arg2 = registerWalletSeedResponseHandle(__arg2) } return } @@ -618,7 +581,7 @@ func SKY_api_Client_UnconfirmedTransactions(_c C.Client__Handle, _addrs []string } //export SKY_api_Client_InjectTransaction -func SKY_api_Client_InjectTransaction(_c C.Client__Handle, _rawTx C.Transaction__Handle, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_api_Client_InjectTransaction(_c C.Client__Handle, _rawTx C.Transaction__Handle, _arg1 *string) (____error_code uint32) { c, okc := lookupClientHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE @@ -633,7 +596,7 @@ func SKY_api_Client_InjectTransaction(_c C.Client__Handle, _rawTx C.Transaction_ __arg1, ____return_err := c.InjectTransaction(rawTx) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg1, _arg1) + *_arg1 = __arg1 } return } @@ -654,7 +617,7 @@ func SKY_api_Client_ResendUnconfirmedTransactions(_c C.Client__Handle, _arg0 *C. } //export SKY_api_Client_RawTransaction -func SKY_api_Client_RawTransaction(_c C.Client__Handle, _txid string, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_api_Client_RawTransaction(_c C.Client__Handle, _txid string, _arg1 *string) (____error_code uint32) { c, okc := lookupClientHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE @@ -664,7 +627,7 @@ func SKY_api_Client_RawTransaction(_c C.Client__Handle, _txid string, _arg1 *C.G __arg1, ____return_err := c.RawTransaction(txid) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg1, _arg1) + *_arg1 = __arg1 } return } @@ -763,3 +726,85 @@ func SKY_api_Client_DecryptWallet(_c C.Client__Handle, _id string, _password str } return } + +//export SKY_api_Client_CreateWallet +func SKY_api_Client_CreateWallet(_c C.Client__Handle, _cwo C.CreateWalletOptions__Handle, _arg2 *C.WalletResponse__Handle) (____error_code uint32) { + c, okc := lookupClientHandle(_c) + if !okc { + ____error_code = SKY_BAD_HANDLE + return + } + cwo, okcwo := lookupCreateWalletOptionsHandle(_cwo) + if !okcwo { + ____error_code = SKY_BAD_HANDLE + return + } + wr, ____return_err := c.CreateWallet(*cwo) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + *_arg2 = registerWalletResponseHandle(wr) + } + return +} + +//export SKY_api_Client_InjectTransactionNoBroadcast +func SKY_api_Client_InjectTransactionNoBroadcast(_c C.Client__Handle, _txn C.Transaction__Handle, _arg0 *string) (____error_code uint32) { + c, okc := lookupClientHandle(_c) + if !okc { + ____error_code = SKY_BAD_HANDLE + return + } + txn, oktxn := lookupTransactionHandle(_txn) + if !oktxn { + ____error_code = SKY_BAD_HANDLE + return + } + arg0, ____return_err := c.InjectTransactionNoBroadcast(txn) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + + *_arg0 = arg0 + } + return +} + +//export SKY_api_Client_InjectEncodedTransactionNoBroadcast +func SKY_api_Client_InjectEncodedTransactionNoBroadcast(_c C.Client__Handle, rawtx string, _arg0 *string) (____error_code uint32) { + c, okc := lookupClientHandle(_c) + if !okc { + ____error_code = SKY_BAD_HANDLE + return + } + + arg0, ____return_err := c.InjectEncodedTransactionNoBroadcast(rawtx) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + + *_arg0 = arg0 + } + return +} + +//export SKY_api_Client_RecoverWallet +func SKY_api_Client_RecoverWallet(_c C.Client__Handle, _req C.WalletRecoverRequest__Handle, _arg2 *C.WalletResponse__Handle) (____error_code uint32) { + c, okc := lookupClientHandle(_c) + if !okc { + ____error_code = SKY_BAD_HANDLE + return + } + + req, okreq := lookupWalletRecoverRequestHandle(_req) + if !okreq { + ____error_code = SKY_BAD_HANDLE + return + } + + arg2, ____return_err := c.RecoverWallet(*req) + ____error_code = libErrorCode(____return_err) + + if ____return_err == nil { + *_arg2 = registerWalletResponseHandle(arg2) + } + return + +} diff --git a/lib/cgo/api.wallet.go b/lib/cgo/api.wallet.go index 90b218dc5..b477b1d6c 100644 --- a/lib/cgo/api.wallet.go +++ b/lib/cgo/api.wallet.go @@ -18,7 +18,7 @@ func SKY_api_NewWalletResponse(_w C.Wallet__Handle, _arg1 *C.WalletResponse__Han ____error_code = SKY_BAD_HANDLE return } - __arg1, ____return_err := api.NewWalletResponse(w) + __arg1, ____return_err := api.NewWalletResponse(*w) ____error_code = libErrorCode(____return_err) if ____return_err == nil { *_arg1 = registerWalletResponseHandle(__arg1) diff --git a/lib/cgo/cipher.address.go b/lib/cgo/cipher.address.go index 843cb8f5c..b1407911e 100644 --- a/lib/cgo/cipher.address.go +++ b/lib/cgo/cipher.address.go @@ -84,8 +84,8 @@ func SKY_cipher_Address_Verify(_addr *C.cipher__Address, _key *C.cipher__PubKey) //export SKY_cipher_Address_String func SKY_cipher_Address_String(_addr *C.cipher__Address, _arg1 *C.GoString_) (____error_code uint32) { addr := (*cipher.Address)(unsafe.Pointer(_addr)) - s := addr.String() - copyString(s, _arg1) + __arg1 := addr.String() + copyString(__arg1, _arg1) return } diff --git a/lib/cgo/cipher.base58.base58.go b/lib/cgo/cipher.base58.base58.go index ec557dda4..04dca2a9c 100644 --- a/lib/cgo/cipher.base58.base58.go +++ b/lib/cgo/cipher.base58.base58.go @@ -20,6 +20,10 @@ import "C" //export SKY_base58_Hex2Base58 func SKY_base58_Hex2Base58(_val []byte, _arg1 *C.GoString_) (____error_code uint32) { val := *(*[]byte)(unsafe.Pointer(&_val)) + if val == nil { + ____error_code = SKY_BAD_HANDLE + return + } __arg1 := string(base58.Encode(val)) copyString(__arg1, _arg1) return @@ -28,6 +32,10 @@ func SKY_base58_Hex2Base58(_val []byte, _arg1 *C.GoString_) (____error_code uint //export SKY_base58_Encode func SKY_base58_Encode(_bin []byte, _arg1 *C.GoString_) (____error_code uint32) { bin := *(*[]byte)(unsafe.Pointer(&_bin)) + if bin == nil { + ____error_code = SKY_BAD_HANDLE + return + } __arg1 := base58.Encode(bin) copyString(__arg1, _arg1) return @@ -56,3 +64,15 @@ func SKY_base58_String2Hex(_s string, _arg1 *C.GoSlice_) (____error_code uint32) return } + +//export SKY_base58_Hex2String +func SKY_base58_Hex2String(_b []byte, _arg1 *C.GoString_) (____error_code uint32) { + bin := *(*[]byte)(unsafe.Pointer(&_b)) + if bin == nil { + ____error_code = SKY_BAD_HANDLE + return + } + __arg1 := hex.EncodeToString(bin) + copyString(__arg1, _arg1) + return +} diff --git a/lib/cgo/cipher.bip32.bip32.go b/lib/cgo/cipher.bip32.bip32.go new file mode 100644 index 000000000..7ba95deb5 --- /dev/null +++ b/lib/cgo/cipher.bip32.bip32.go @@ -0,0 +1,435 @@ +package main + +import ( + "reflect" + "unsafe" + + "github.com/skycoin/skycoin/src/cipher/bip32" +) + +/* + + #include + #include + + #include "skytypes.h" +*/ +import "C" + +//export SKY_bip32_NewMasterKey +func SKY_bip32_NewMasterKey(_seed []byte, _pk *C.PrivateKey__Handle) (___error_code uint32) { + seed := _seed + pk, ___return_error := bip32.NewMasterKey(seed) + ___error_code = libErrorCode(___return_error) + if ___return_error == nil { + *_pk = registerPrivateKeyHandle(pk) + } + return +} + +//export SKY_bip32_NewPrivateKeyFromPath +func SKY_bip32_NewPrivateKeyFromPath(_seed []byte, _p string, _pk *C.PrivateKey__Handle) (___error_code uint32) { + seed := _seed + p := string(_p) + pk, ___return_error := bip32.NewPrivateKeyFromPath(seed, p) + ___error_code = libErrorCode(___return_error) + if ___return_error == nil { + *_pk = registerPrivateKeyHandle(pk) + } + return +} + +//export SKY_bip32_PrivateKey_DeriveSubpath +func SKY_bip32_PrivateKey_DeriveSubpath(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_, _pk1 *C.PrivateKey__Handle) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + node := *(*[]bip32.PathNode)(unsafe.Pointer(&_arg0)) + pk1, ____return_err := pk.DeriveSubpath(node) + ___error_code = libErrorCode(____return_err) + + if ____return_err == nil { + *_pk1 = registerPrivateKeyHandle(pk1) + } + return +} + +//export SKY_bip32_PrivateKey_Publickey +func SKY_bip32_PrivateKey_Publickey(_pk C.PrivateKey__Handle, _pp *C.PublicKey__Handle) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + pp := pk.PublicKey() + *_pp = registerPublicKeyHandle(pp) + return +} + +//export SKY_bip32_PrivateKey_Fingerprint +func SKY_bip32_PrivateKey_Fingerprint(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Fingerprint() + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PrivateKey_Identifier +func SKY_bip32_PrivateKey_Identifier(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Identifier() + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PublicKey_Fingerprint +func SKY_bip32_PublicKey_Fingerprint(_pk C.PublicKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPublicKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Fingerprint() + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PublicKey_Identifier +func SKY_bip32_PublicKey_Identifier(_pk C.PublicKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPublicKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Identifier() + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PrivateKey_NewPrivateChildKey +func SKY_bip32_PrivateKey_NewPrivateChildKey(_pk C.PrivateKey__Handle, _childIdx uint32, _arg0 *C.PrivateKey__Handle) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + childIdx := uint32(_childIdx) + __arg0, ___return_error := pk.NewPrivateChildKey(childIdx) + ___error_code = libErrorCode(___return_error) + if ___return_error == nil { + *_arg0 = registerPrivateKeyHandle(__arg0) + } + return +} + +//export SKY_bip32_PrivateKey_NewPublicChildKey +func SKY_bip32_PrivateKey_NewPublicChildKey(_pk C.PrivateKey__Handle, _childIdx uint32, _arg0 *C.PublicKey__Handle) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + childIdx := uint32(_childIdx) + __arg0, ___return_error := pk.NewPublicChildKey(childIdx) + ___error_code = libErrorCode(___return_error) + if ___return_error == nil { + *_arg0 = registerPublicKeyHandle(__arg0) + } + return +} + +//export SKY_bip32_PublicKey_NewPublicChildKey +func SKY_bip32_PublicKey_NewPublicChildKey(_pk C.PublicKey__Handle, _childIdx uint32, _arg0 *C.PublicKey__Handle) (___error_code uint32) { + pk, okpk := lookupPublicKeyHandle(_pk) + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + childIdx := uint32(_childIdx) + __arg0, ___return_error := pk.NewPublicChildKey(childIdx) + ___error_code = libErrorCode(___return_error) + if ___return_error == nil { + *_arg0 = registerPublicKeyHandle(__arg0) + } + return +} + +//export SKY_bip32_PrivateKey_Serialize +func SKY_bip32_PrivateKey_Serialize(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Serialize() + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + + return +} + +//export SKY_bip32_PublicKey_Serialize +func SKY_bip32_PublicKey_Serialize(_pk C.PublicKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Serialize() + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PrivateKey_String +func SKY_bip32_PrivateKey_String(_pk C.PrivateKey__Handle, _arg0 *C.GoString_) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.String() + copyString(__arg0, _arg0) + return +} + +//export SKY_bip32_PublicKey_String +func SKY_bip32_PublicKey_String(_pk C.PublicKey__Handle, _arg0 *C.GoString_) (___error_code uint32) { + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.String() + copyString(__arg0, _arg0) + return +} + +//export SKY_bip32_DeserializeEncodedPrivateKey +func SKY_bip32_DeserializeEncodedPrivateKey(_xprv string, _arg0 *C.PrivateKey__Handle) (___error_code uint32) { + xprv := string(_xprv) + pk, ___return_err := bip32.DeserializeEncodedPrivateKey(xprv) + ___error_code = libErrorCode(___return_err) + if ___return_err == nil { + *_arg0 = registerPrivateKeyHandle(pk) + } + return +} + +//export SKY_bip32_DeserializePrivateKey +func SKY_bip32_DeserializePrivateKey(_data []byte, _arg0 *C.PrivateKey__Handle) (___error_code uint32) { + data := _data + pk, ___return_err := bip32.DeserializePrivateKey(data) + ___error_code = libErrorCode(___return_err) + if ___return_err == nil { + *_arg0 = registerPrivateKeyHandle(pk) + } + return +} + +//export SKY_bip32_DeserializeEncodedPublicKey +func SKY_bip32_DeserializeEncodedPublicKey(_xpub string, _arg0 *C.PublicKey__Handle) (___error_code uint32) { + xpub := string(_xpub) + pk, ___return_err := bip32.DeserializeEncodedPublicKey(xpub) + ___error_code = libErrorCode(___return_err) + if ___return_err == nil { + *_arg0 = registerPublicKeyHandle(pk) + } + return +} + +//export SKY_bip32_DeserializePublicKey +func SKY_bip32_DeserializePublicKey(_data []byte, _arg0 *C.PublicKey__Handle) (___error_code uint32) { + + data := _data + pk, ___return_err := bip32.DeserializePublicKey(data) + ___error_code = libErrorCode(___return_err) + if ___return_err == nil { + *_arg0 = registerPublicKeyHandle(pk) + } + return +} + +//export SKY_bip32_PrivateKey_GetKey +func SKY_bip32_PrivateKey_GetKey(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Key + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PublicKey_GetKey +func SKY_bip32_PublicKey_GetKey(_pk C.PublicKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + __arg0 := pk.Key + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PrivateKey_GetDepth +func SKY_bip32_PrivateKey_GetDepth(_pk C.PrivateKey__Handle, _arg0 *byte) (___error_code uint32) { + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + arg0 := pk.Depth + *_arg0 = arg0 + return +} + +//export SKY_bip32_PublicKey_GetDepth +func SKY_bip32_PublicKey_GetDepth(_pk C.PublicKey__Handle, _arg0 *byte) (___error_code uint32) { + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + arg0 := pk.Depth + *_arg0 = arg0 + return +} + +//export SKY_bip32_PrivateKey_ChildNumber +func SKY_bip32_PrivateKey_ChildNumber(_pk C.PrivateKey__Handle, _arg0 *uint32) (___error_code uint32) { + + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + __arg0 := pk.ChildNumber() + *_arg0 = uint32(__arg0) + return +} + +//export SKY_bip32_PublicKey_ChildNumber +func SKY_bip32_PublicKey_ChildNumber(_pk C.PublicKey__Handle, _arg0 *uint32) (___error_code uint32) { + + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + __arg0 := uint32(pk.ChildNumber()) + *_arg0 = __arg0 + return +} + +//export SKY_bip32_PrivateKey_GetChainCode +func SKY_bip32_PrivateKey_GetChainCode(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + __arg0 := pk.ChainCode + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PublicKey_GetChainCode +func SKY_bip32_PublicKey_GetChainCode(_pk C.PublicKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + __arg0 := pk.ChainCode + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PrivateKey_GetVersion +func SKY_bip32_PrivateKey_GetVersion(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + __arg0 := pk.Version + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PublicKey_GetVersion +func SKY_bip32_PublicKey_GetVersion(_pk C.PublicKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + copyToGoSlice(reflect.ValueOf(pk.Version), _arg0) + return +} + +//export SKY_bip32_PrivateKey_GetParentFingerprint +func SKY_bip32_PrivateKey_GetParentFingerprint(_pk C.PrivateKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + + pk, okpk := lookupPrivateKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + __arg0 := pk.ParentFingerprint + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_bip32_PublicKey_GetParentFingerprint +func SKY_bip32_PublicKey_GetParentFingerprint(_pk C.PublicKey__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + + pk, okpk := lookupPublicKeyHandle(_pk) + + if !okpk { + ___error_code = SKY_BAD_HANDLE + return + } + + __arg0 := pk.ParentFingerprint + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} diff --git a/lib/cgo/cipher.bip32.path.go b/lib/cgo/cipher.bip32.path.go new file mode 100644 index 000000000..09c544d62 --- /dev/null +++ b/lib/cgo/cipher.bip32.path.go @@ -0,0 +1,69 @@ +package main + +import ( + "unsafe" + + "github.com/skycoin/skycoin/src/cipher/bip32" +) + +/* + + #include + #include + + #include "skytypes.h" +*/ +import "C" + +//export SKY_bip32_PathNode_Hardened +func SKY_bip32_PathNode_Hardened(_pk *C.bip32__PathNode) (____error_code uint32) { + pk := (*bip32.PathNode)(unsafe.Pointer(_pk)) + err := pk.Hardened() + ____error_code = 1 + if !err { + ____error_code = 0 + } + return +} + +//export SKY_bip32_ParsePath +func SKY_bip32_ParsePath(_p string, _arg0 *C.Path__Handle) (____error_code uint32) { + + p, err := bip32.ParsePath(_p) + ____error_code = libErrorCode(err) + if err == nil { + *_arg0 = registerPathHandle(p) + } + return +} + +//export SKY_bip32_Path_Count +func SKY_bip32_Path_Count(handle C.Path__Handle, _arg0 *int) (____error_code uint32) { + p, okp := lookupPathHandle(handle) + + if !okp { + ____error_code = SKY_BAD_HANDLE + return + } + + *_arg0 = len(p.Elements) + return +} + +//export SKY_bip32_Path_GetElements +func SKY_bip32_Path_GetElements(handle C.Path__Handle, post int, _arg0 *C.bip32__PathNode) (____error_code uint32) { + p, okp := lookupPathHandle(handle) + + if !okp { + ____error_code = SKY_BAD_HANDLE + return + } + + if len(p.Elements) <= post { + ____error_code = SKY_BAD_HANDLE + return + } + + *_arg0 = *(*C.bip32__PathNode)(unsafe.Pointer(&p.Elements[post])) + return +} diff --git a/lib/cgo/cipher.go-bip39.bip39.go b/lib/cgo/cipher.bip39.bip39.go similarity index 61% rename from lib/cgo/cipher.go-bip39.bip39.go rename to lib/cgo/cipher.bip39.bip39.go index 2ec5a8676..28f61a554 100644 --- a/lib/cgo/cipher.go-bip39.bip39.go +++ b/lib/cgo/cipher.bip39.bip39.go @@ -4,7 +4,7 @@ import ( "reflect" "unsafe" - gobip39 "github.com/skycoin/skycoin/src/cipher/bip39" + "github.com/skycoin/skycoin/src/cipher/bip39" ) /* @@ -17,33 +17,33 @@ import ( import "C" //export SKY_bip39_NewDefaultMnemomic -func SKY_bip39_NewDefaultMnemomic(_arg0 *C.GoString_) (____error_code uint32) { - __arg0, ____return_err := gobip39.NewDefaultMnemonic() +func SKY_bip39_NewDefaultMnemomic(_arg0 *string) (____error_code uint32) { + __arg0, ____return_err := bip39.NewDefaultMnemonic() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg0, _arg0) + *_arg0 = __arg0 } return } //export SKY_bip39_NewEntropy -func SKY_bip39_NewEntropy(_bitSize int, _arg1 *C.GoSlice_) (____error_code uint32) { +func SKY_bip39_NewEntropy(_bitSize int, _arg1 *[]byte) (____error_code uint32) { bitSize := _bitSize - __arg1, ____return_err := gobip39.NewEntropy(bitSize) + __arg1, ____return_err := bip39.NewEntropy(bitSize) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg1), _arg1) + *_arg1 = __arg1 } return } //export SKY_bip39_NewMnemonic -func SKY_bip39_NewMnemonic(_entropy []byte, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_bip39_NewMnemonic(_entropy []byte, _arg1 *string) (____error_code uint32) { entropy := *(*[]byte)(unsafe.Pointer(&_entropy)) - __arg1, ____return_err := gobip39.NewMnemonic(entropy) + __arg1, ____return_err := bip39.NewMnemonic(entropy) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg1, _arg1) + *_arg1 = __arg1 } return } @@ -51,7 +51,7 @@ func SKY_bip39_NewMnemonic(_entropy []byte, _arg1 *C.GoString_) (____error_code //export SKY_bip39_ValidateMnemonic func SKY_bip39_ValidateMnemonic(_mnemonic string) (____error_code uint32) { mnemonic := _mnemonic - ____return_err := gobip39.ValidateMnemonic(mnemonic) + ____return_err := bip39.ValidateMnemonic(mnemonic) ____error_code = libErrorCode(____return_err) return } @@ -60,7 +60,7 @@ func SKY_bip39_ValidateMnemonic(_mnemonic string) (____error_code uint32) { func SKY_bip39_NewSeed(_mnemonic string, _password string, _arg1 *C.GoSlice_) (____error_code uint32) { mnemonic := _mnemonic password := _password - __arg1, ____return_err := gobip39.NewSeed(mnemonic, password) + __arg1, ____return_err := bip39.NewSeed(mnemonic, password) ____error_code = libErrorCode(____return_err) if ____return_err == nil { copyToGoSlice(reflect.ValueOf(__arg1), _arg1) diff --git a/lib/cgo/cipher.bip44.bip44.go b/lib/cgo/cipher.bip44.bip44.go new file mode 100644 index 000000000..5afa95cc0 --- /dev/null +++ b/lib/cgo/cipher.bip44.bip44.go @@ -0,0 +1,102 @@ +package main + +import ( + "github.com/skycoin/skycoin/src/cipher/bip44" +) + +/* + + #include + #include + + #include "skytypes.h" +*/ +import "C" + +//export SKY_bip44_NewCoin +func SKY_bip44_NewCoin(_seed []byte, _coinType uint32, _arg0 *C.Coin__Handle) (___err_code uint32) { + __arg0, ___return_err := bip44.NewCoin(_seed, bip44.CoinType(_coinType)) + ___err_code = libErrorCode(___return_err) + if ___return_err == nil { + *_arg0 = registerCoinHandle(__arg0) + } + return +} + +//export SKY_bip44_Coin_Account +func SKY_bip44_Coin_Account(_c C.Coin__Handle, account uint32, _arg0 *C.Account__Handle) (___err_code uint32) { + c, okc := lookupCoinHandle(_c) + if !okc { + ___err_code = SKY_BAD_HANDLE + return + } + ac, err := c.Account(account) + ___err_code = libErrorCode(err) + if err == nil { + *_arg0 = registerAccountHandle(ac) + } + return +} + +//export SKY_bip44_Account_External +func SKY_bip44_Account_External(_a C.Account__Handle, _arg0 *C.PrivateKey__Handle) (___err_code uint32) { + a, oka := lookupAccountHandle(_a) + if !oka { + ___err_code = SKY_BAD_HANDLE + return + } + + p, __return_err := a.External() + ___err_code = libErrorCode(__return_err) + if __return_err == nil { + *_arg0 = registerPrivateKeyHandle(p) + + } + return +} + +//export SKY_bip44_Account_Change +func SKY_bip44_Account_Change(_a C.Account__Handle, _arg0 *C.PrivateKey__Handle) (___err_code uint32) { + a, oka := lookupAccountHandle(_a) + if !oka { + ___err_code = SKY_BAD_HANDLE + return + } + + p, __return_err := a.Change() + ___err_code = libErrorCode(__return_err) + if __return_err == nil { + *_arg0 = registerPrivateKeyHandle(p) + + } + return +} + +//export SKY_bip44_Account_String +func SKY_bip44_Account_String(_a C.Account__Handle, _arg0 *C.GoString_) (___err_code uint32) { + + a, oka := lookupAccountHandle(_a) + if !oka { + + ___err_code = SKY_BAD_HANDLE + return + } + + __arg0 := a.String() + copyString(__arg0, _arg0) + return +} + +//export SKY_bip44_Account_GetPrivateKey +func SKY_bip44_Account_GetPrivateKey(_a C.Account__Handle, _arg0 *C.PrivateKey__Handle) (___err_code uint32) { + + a, oka := lookupAccountHandle(_a) + if !oka { + + ___err_code = SKY_BAD_HANDLE + return + } + + *_arg0 = registerPrivateKeyHandle(a.PrivateKey) + return +} diff --git a/lib/cgo/cipher.bitcoin.go b/lib/cgo/cipher.bitcoin.go index 34f140288..b66905dc8 100644 --- a/lib/cgo/cipher.bitcoin.go +++ b/lib/cgo/cipher.bitcoin.go @@ -109,4 +109,4 @@ func SKY_cipher_BitcoinAddress_Checksum(_addr *C.cipher__BitcoinAddress, _arg0 * addr := (*cipher.BitcoinAddress)(unsafe.Pointer(_addr)) cs := addr.Checksum() C.memcpy(unsafe.Pointer(_arg0), unsafe.Pointer(&cs[0]), C.size_t(len(cs))) -} +} \ No newline at end of file diff --git a/lib/cgo/cipher.crypto.go b/lib/cgo/cipher.crypto.go index d9cbb9f93..38faf5ea4 100644 --- a/lib/cgo/cipher.crypto.go +++ b/lib/cgo/cipher.crypto.go @@ -18,8 +18,8 @@ import "C" //export SKY_cipher_RandByte func SKY_cipher_RandByte(_n int, _arg1 *C.GoSlice_) (____error_code uint32) { - b := cipher.RandByte(_n) - copyToGoSlice(reflect.ValueOf(b), _arg1) + __arg1 := cipher.RandByte(_n) + copyToGoSlice(reflect.ValueOf(__arg1), _arg1) return } @@ -86,8 +86,8 @@ func SKY_cipher_PubKey_Verify(_pk *C.cipher__PubKey) (____error_code uint32) { //export SKY_cipher_PubKey_Hex func SKY_cipher_PubKey_Hex(_pk *C.cipher__PubKey, _arg1 *C.GoString_) (____error_code uint32) { pk := (*cipher.PubKey)(unsafe.Pointer(_pk)) - s := pk.Hex() - copyString(s, _arg1) + __arg1 := pk.Hex() + copyString(__arg1, _arg1) return SKY_OK } @@ -132,8 +132,8 @@ func SKY_cipher_SecKey_Verify(_sk *C.cipher__SecKey) (____error_code uint32) { //export SKY_cipher_SecKey_Hex func SKY_cipher_SecKey_Hex(_sk *C.cipher__SecKey, _arg1 *C.GoString_) (____error_code uint32) { sk := (*cipher.SecKey)(unsafe.Pointer(_sk)) - s := sk.Hex() - copyString(s, _arg1) + __arg1 := sk.Hex() + copyString(__arg1, _arg1) return } @@ -173,7 +173,8 @@ func SKY_cipher_SigFromHex(_s string, _arg1 *C.cipher__Sig) (____error_code uint //export SKY_cipher_Sig_Hex func SKY_cipher_Sig_Hex(_s *C.cipher__Sig, _arg1 *C.GoString_) (____error_code uint32) { s := (*cipher.Sig)(unsafe.Pointer(_s)) - copyString(s.Hex(), _arg1) + __arg1 := s.Hex() + copyString(__arg1,_arg1) return } @@ -285,3 +286,27 @@ func SKY_cipher_CheckSecKeyHash(_seckey *C.cipher__SecKey, _hash *C.cipher__SHA2 ____error_code = libErrorCode(err) return } + +//export SKY_cipher_Sig_String +func SKY_cipher_Sig_String(_s *C.cipher__Sig, _arg1 *C.GoString_) (____error_code uint32) { + s := (*cipher.Sig)(unsafe.Pointer(_s)) + __arg1 := s.String() + copyString(__arg1,_arg1) + return +} + +//export SKY_cipher_VerifySignatureRecoverPubKey +func SKY_cipher_VerifySignatureRecoverPubKey(_s *C.cipher__Sig, _hash *C.cipher__SHA256) (____error_code uint32) { + s := (*cipher.Sig)(unsafe.Pointer(_s)) + hash := (*cipher.SHA256)(unsafe.Pointer(_hash)) + __return_err := cipher.VerifySignatureRecoverPubKey(*s, *hash) + ____error_code = libErrorCode(__return_err) + return +} + +//export SKY_cipher_Sig_Null +func SKY_cipher_Sig_Null(_s *C.cipher__Sig, _arg1 *bool) (____error_code uint32) { + s := (*cipher.Sig)(unsafe.Pointer(_s)) + *_arg1 = s.Null() + return +} diff --git a/lib/cgo/cipher.hash.go b/lib/cgo/cipher.hash.go index 3509e2e15..908145a95 100644 --- a/lib/cgo/cipher.hash.go +++ b/lib/cgo/cipher.hash.go @@ -36,7 +36,6 @@ func SKY_cipher_HashRipemd160(_data []byte, _arg1 *C.cipher__Ripemd160) (____err //export SKY_cipher_SHA256_Set func SKY_cipher_SHA256_Set(_g *C.cipher__SHA256, _b []byte) (____error_code uint32) { g := (*cipher.SHA256)(unsafe.Pointer(_g)) - err := g.Set(_b) ____error_code = libErrorCode(err) return @@ -45,7 +44,8 @@ func SKY_cipher_SHA256_Set(_g *C.cipher__SHA256, _b []byte) (____error_code uint //export SKY_cipher_SHA256_Hex func SKY_cipher_SHA256_Hex(_g *C.cipher__SHA256, _arg1 *C.GoString_) (____error_code uint32) { g := (*cipher.SHA256)(unsafe.Pointer(_g)) - copyString(g.Hex(), _arg1) + __arg1 := g.Hex() + copyString(__arg1, _arg1) return } diff --git a/lib/cgo/cipher.secp256k1-go.secp256k1.go b/lib/cgo/cipher.secp256k1-go.secp256k1.go index 87968cb93..88bdf4cb6 100644 --- a/lib/cgo/cipher.secp256k1-go.secp256k1.go +++ b/lib/cgo/cipher.secp256k1-go.secp256k1.go @@ -21,9 +21,11 @@ func SKY_secp256k1_PubkeyFromSeckey(__seckey []byte, _arg1 *C.GoSlice_) (____err __arg1 := secp256k1.PubkeyFromSeckey(seckey) if __arg1 != nil { copyToGoSlice(reflect.ValueOf(__arg1), _arg1) - return SKY_OK + ____error_code = SKY_OK + return } - return SKY_ERROR + ____error_code = SKY_ERROR + return } //export SKY_secp256k1_VerifyPubkey @@ -47,7 +49,9 @@ func SKY_secp256k1_ECDH(_pub []byte, _sec []byte, _arg1 *C.GoSlice_) (____error_ __arg1 := secp256k1.ECDH(pubkey, seckey) if __arg1 != nil { copyToGoSlice(reflect.ValueOf(__arg1), _arg1) - return SKY_OK + ____error_code = SKY_OK + return } - return SKY_ERROR + ____error_code = SKY_ERROR + return } diff --git a/lib/cgo/cli.add_private_key.go b/lib/cgo/cli.add_private_key.go index 2620fe7aa..36557405e 100644 --- a/lib/cgo/cli.add_private_key.go +++ b/lib/cgo/cli.add_private_key.go @@ -14,8 +14,8 @@ import ( import "C" //export SKY_cli_AddPrivateKey -func SKY_cli_AddPrivateKey(_wlt C.Wallet__Handle, _key string) (____error_code uint32) { - wlt, okwlt := lookupWalletHandle(_wlt) +func SKY_cli_AddPrivateKey(_wlt C.CollectionWallet__Handle, _key string) (____error_code uint32) { + wlt, okwlt := lookupCollectionWalletHandle(_wlt) if !okwlt { ____error_code = SKY_BAD_HANDLE return diff --git a/lib/cgo/cli.check_balance.go b/lib/cgo/cli.check_balance.go index bfca6865e..4273d6bbe 100644 --- a/lib/cgo/cli.check_balance.go +++ b/lib/cgo/cli.check_balance.go @@ -1,5 +1,11 @@ package main +import ( + "unsafe" + + cli "github.com/skycoin/skycoin/src/cli" +) + /* #include @@ -9,18 +15,18 @@ package main */ import "C" -// //export SKY_cli_GetBalanceOfAddresses -// func SKY_cli_GetBalanceOfAddresses(_c C.WebRpcClient__Handle, _addrs []string, _arg2 *C.BalanceResult_Handle) (____error_code uint32) { -// c, okc := lookupWebRpcClientHandle(_c) -// if !okc { -// ____error_code = SKY_BAD_HANDLE -// return -// } -// addrs := *(*[]string)(unsafe.Pointer(&_addrs)) -// __arg2, ____return_err := cli.GetBalanceOfAddresses(c, addrs) -// ____error_code = libErrorCode(____return_err) -// if ____return_err == nil { -// *_arg2 = registerBalanceResultHandle(__arg2) -// } -// return -// } +//export SKY_cli_GetBalanceOfAddresses +func SKY_cli_GetBalanceOfAddresses(_c C.GetOutputser__Handle, _addrs []string, _arg2 *C.BalanceResult_Handle) (____error_code uint32) { + c, okc := lookupGetOutputserHandle(_c) + if !okc { + ____error_code = SKY_BAD_HANDLE + return + } + addrs := *(*[]string)(unsafe.Pointer(&_addrs)) + __arg2, ____return_err := cli.GetBalanceOfAddresses(*c, addrs) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + *_arg2 = registerBalanceResultHandle(__arg2) + } + return +} diff --git a/lib/cgo/cli.cli.go b/lib/cgo/cli.cli.go index 9b585bd8a..c43bf5a8b 100644 --- a/lib/cgo/cli.cli.go +++ b/lib/cgo/cli.cli.go @@ -1,7 +1,6 @@ package main import ( - "reflect" "unsafe" "github.com/skycoin/skycoin/src/cli" @@ -26,29 +25,15 @@ func SKY_cli_LoadConfig(_arg0 *C.Config__Handle) (____error_code uint32) { return } -//export SKY_cli_Config_FullWalletPath -func SKY_cli_Config_FullWalletPath(_c C.Config__Handle, _arg0 *C.GoString_) (____error_code uint32) { - __c, okc := lookupConfigHandle(_c) - if !okc { - ____error_code = SKY_BAD_HANDLE - return - } - c := *__c - __arg0 := c.FullWalletPath() - copyString(__arg0, _arg0) - return -} - //export SKY_cli_Config_FullDBPath -func SKY_cli_Config_FullDBPath(_c C.Config__Handle, _arg0 *C.GoString_) (____error_code uint32) { +func SKY_cli_Config_FullDBPath(_c C.Config__Handle, _arg0 *string) (____error_code uint32) { __c, okc := lookupConfigHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE return } c := *__c - __arg0 := c.FullDBPath() - copyString(__arg0, _arg0) + *_arg0 = c.FullDBPath() return } @@ -80,23 +65,23 @@ func SKY_cli_NewPasswordReader(_password []byte, passwordReader *C.PasswordReade } //export SKY_cli_PasswordFromBytes_Password -func SKY_cli_PasswordFromBytes_Password(_p *C.cli__PasswordFromBytes, _arg0 *C.GoSlice_) (____error_code uint32) { +func SKY_cli_PasswordFromBytes_Password(_p *C.cli__PasswordFromBytes, _arg0 *[]byte) (____error_code uint32) { p := *(*cli.PasswordFromBytes)(unsafe.Pointer(_p)) __arg0, ____return_err := p.Password() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + *_arg0 = __arg0 } return } //export SKY_cli_PasswordFromTerm_Password -func SKY_cli_PasswordFromTerm_Password(_arg0 *C.GoSlice_) (____error_code uint32) { +func SKY_cli_PasswordFromTerm_Password(_arg0 *[]byte) (____error_code uint32) { p := cli.PasswordFromTerm{} __arg0, ____return_err := p.Password() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + *_arg0 = __arg0 } return } diff --git a/lib/cgo/cli.create_rawtx.go b/lib/cgo/cli.create_rawtx.go index e8959d75f..f16306413 100644 --- a/lib/cgo/cli.create_rawtx.go +++ b/lib/cgo/cli.create_rawtx.go @@ -19,30 +19,6 @@ import ( */ import "C" -// //export SKY_cli_CreateRawTxFromAddress -// func SKY_cli_CreateRawTxFromAddress(_c C.WebRpcClient__Handle, _addr, _walletFile, _chgAddr string, _toAddrs []C.cli__SendAmount, pwd C.PasswordReader__Handle, _arg4 *C.Transaction__Handle) (____error_code uint32) { -// c, okc := lookupWebRpcClientHandle(_c) -// if !okc { -// ____error_code = SKY_BAD_HANDLE -// return -// } -// addr := _addr -// walletFile := _walletFile -// chgAddr := _chgAddr -// toAddrs := *(*[]cli.SendAmount)(unsafe.Pointer(&_toAddrs)) -// pr, okp := lookupPasswordReaderHandle(pwd) -// if !okp { -// ____error_code = SKY_BAD_HANDLE -// return -// } -// __arg4, ____return_err := cli.CreateRawTxFromAddress(c, addr, walletFile, chgAddr, toAddrs, *pr) -// ____error_code = libErrorCode(____return_err) -// if ____return_err == nil { -// *_arg4 = registerTransactionHandle(__arg4) -// } -// return -// } - //export SKY_cli_NewTransaction func SKY_cli_NewTransaction(_utxos []C.transaction__UxBalance, _keys []C.cipher__SecKey, _outs []C.coin__TransactionOutput, _arg3 *C.Transaction__Handle) (____error_code uint32) { utxos := *(*[]transaction.UxBalance)(unsafe.Pointer(&_utxos)) diff --git a/lib/cgo/cli.generate_addrs.go b/lib/cgo/cli.generate_addrs.go index da13765e6..a70e61526 100644 --- a/lib/cgo/cli.generate_addrs.go +++ b/lib/cgo/cli.generate_addrs.go @@ -35,31 +35,31 @@ func SKY_cli_GenerateAddressesInFile(_walletFile string, _num uint64, pwd C.Pass } //export SKY_cli_FormatAddressesAsJSON -func SKY_cli_FormatAddressesAsJSON(_addrs []C.cipher__Address, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_cli_FormatAddressesAsJSON(_addrs []C.cipher__Address, _arg1 *string) (____error_code uint32) { addrs := *(*[]cipher.Address)(unsafe.Pointer(&_addrs)) __addrs := toAddresserArray(addrs) __arg1, ____return_err := cli.FormatAddressesAsJSON(__addrs) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg1, _arg1) + *_arg1 = __arg1 } return } //export SKY_cli_FormatAddressesAsJoinedArray -func SKY_cli_FormatAddressesAsJoinedArray(_addrs []C.cipher__Address, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_cli_FormatAddressesAsJoinedArray(_addrs []C.cipher__Address, _arg1 *string) (____error_code uint32) { addrs := *(*[]cipher.Address)(unsafe.Pointer(&_addrs)) __addrs := toAddresserArray(addrs) __arg1 := cli.FormatAddressesAsJoinedArray(__addrs) - copyString(__arg1, _arg1) + *_arg1 = __arg1 return } //export SKY_cli_AddressesToStrings -func SKY_cli_AddressesToStrings(_addrs []C.cipher__Address, _arg1 *C.GoSlice_) (____error_code uint32) { +func SKY_cli_AddressesToStrings(_addrs []C.cipher__Address, _arg1 *[]string) (____error_code uint32) { addrs := *(*[]cipher.Address)(unsafe.Pointer(&_addrs)) __addrs := toAddresserArray(addrs) - __arg1 := cli.AddressesToStrings(__addrs) - copyToGoSlice(reflect.ValueOf(__arg1), _arg1) + *_arg1 = cli.AddressesToStrings(__addrs) + return } diff --git a/lib/cgo/cli.generate_wallet.go b/lib/cgo/cli.generate_wallet.go index 48714c990..4de61f0f9 100644 --- a/lib/cgo/cli.generate_wallet.go +++ b/lib/cgo/cli.generate_wallet.go @@ -13,27 +13,8 @@ import ( */ import "C" -//export SKY_cli_GenerateWallet -func SKY_cli_GenerateWallet(_walletFile string, _opts *C.Options__Handle, _numAddrs uint64, _arg3 *C.Wallet__Handle) (____error_code uint32) { - walletFile := _walletFile - __opts, okopts := lookupOptionsHandle(*_opts) - if !okopts { - ____error_code = SKY_BAD_HANDLE - return - } - opts := *__opts - numAddrs := _numAddrs - __arg3, ____return_err := cli.GenerateWallet(walletFile, opts, numAddrs) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - *_arg3 = registerWalletHandle(__arg3) - } - return -} - //export SKY_cli_MakeAlphanumericSeed -func SKY_cli_MakeAlphanumericSeed(_arg0 *C.GoString_) (____error_code uint32) { - __arg0 := cli.MakeAlphanumericSeed() - copyString(__arg0, _arg0) +func SKY_cli_MakeAlphanumericSeed(_arg0 *string) (____error_code uint32) { + *_arg0 = cli.MakeAlphanumericSeed() return } diff --git a/lib/cgo/cli.outputs.go b/lib/cgo/cli.outputs.go index 72bcf1cfb..79760be0d 100644 --- a/lib/cgo/cli.outputs.go +++ b/lib/cgo/cli.outputs.go @@ -1,5 +1,9 @@ package main +import ( + cli "github.com/skycoin/skycoin/src/cli" +) + /* #include @@ -9,39 +13,41 @@ package main */ import "C" -// TODO: Not implement datatype -// //export SKY_cli_GetWalletOutputsFromFile -// func SKY_cli_GetWalletOutputsFromFile(_c C.WebRpcClient__Handle, _walletFile string, _arg2 *C.ReadableUnspentOutputsSummary_Handle) (____error_code uint32) { -// c, okc := lookupWebRpcClientHandle(_c) -// if !okc { -// ____error_code = SKY_BAD_HANDLE -// return -// } -// walletFile := _walletFile -// __arg2, ____return_err := cli.GetWalletOutputsFromFile(c, walletFile) -// ____error_code = libErrorCode(____return_err) -// if ____return_err == nil { -// *_arg2 = registerReadableUnspentOutputsSummaryHandle(__arg2) -// } -// return -// } - -// //export SKY_cli_GetWalletOutputs -// func SKY_cli_GetWalletOutputs(_c C.WebRpcClient__Handle, _wlt *C.Wallet__Handle, _arg2 *C.ReadableUnspentOutputsSummary_Handle) (____error_code uint32) { -// c, okc := lookupWebRpcClientHandle(_c) -// if !okc { -// ____error_code = SKY_BAD_HANDLE -// return -// } -// wlt, okwlt := lookupWalletHandle(*_wlt) -// if !okwlt { -// ____error_code = SKY_BAD_HANDLE -// return -// } -// __arg2, ____return_err := cli.GetWalletOutputs(c, wlt) -// ____error_code = libErrorCode(____return_err) -// if ____return_err == nil { -// *_arg2 = registerReadableUnspentOutputsSummaryHandle(__arg2) -// } -// return -// } +//export SKY_cli_GetWalletOutputsFromFile +func SKY_cli_GetWalletOutputsFromFile(_c C.GetOutputser__Handle, _walletFile string, _arg2 *C.ReadableUnspentOutputsSummary_Handle) (____error_code uint32) { + c, okc := lookupGetOutputserHandle(_c) + if !okc { + ____error_code = SKY_BAD_HANDLE + return + } + walletFile := _walletFile + + ru, ____return_err := cli.GetWalletOutputsFromFile(*c, walletFile) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + + *_arg2 = registerReadableUnspentOutputsSummaryHandle(ru) + + } + return +} + +//export SKY_cli_GetWalletOutputs +func SKY_cli_GetWalletOutputs(_c C.GetOutputser__Handle, _wlt *C.Wallet__Handle, _arg2 *C.ReadableUnspentOutputsSummary_Handle) (____error_code uint32) { + c, okc := lookupGetOutputserHandle(_c) + if !okc { + ____error_code = SKY_BAD_HANDLE + return + } + wlt, okwlt := lookupWalletHandle(*_wlt) + if !okwlt { + ____error_code = SKY_BAD_HANDLE + return + } + __arg2, ____return_err := cli.GetWalletOutputs(*c, *wlt) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + *_arg2 = registerReadableUnspentOutputsSummaryHandle(__arg2) + } + return +} diff --git a/lib/cgo/cli_helper.go b/lib/cgo/cli_helper.go index 9c0d97b73..062cb369d 100644 --- a/lib/cgo/cli_helper.go +++ b/lib/cgo/cli_helper.go @@ -29,35 +29,32 @@ func SKY_cli_CLI_Run(_app C.CLI__Handle) (____error_code uint32) { } //export SKY_cli_Config_GetCoin -func SKY_cli_Config_GetCoin(_c C.Config__Handle, _arg0 *C.GoString_) (____error_code uint32) { +func SKY_cli_Config_GetCoin(_c C.Config__Handle, _arg0 *string) (____error_code uint32) { __c, okc := lookupConfigHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE return } c := *__c - __arg0 := c.Coin - copyString(__arg0, _arg0) + *_arg0 = c.Coin return } //export SKY_cli_Config_GetRPCAddress -func SKY_cli_Config_GetRPCAddress(_c C.Config__Handle, _arg0 *C.GoString_) (____error_code uint32) { +func SKY_cli_Config_GetRPCAddress(_c C.Config__Handle, _arg0 *string) (____error_code uint32) { __c, okc := lookupConfigHandle(_c) if !okc { ____error_code = SKY_BAD_HANDLE return } c := *__c - __arg0 := c.RPCAddress - copyString(__arg0, _arg0) + *_arg0 = c.RPCAddress return } //export SKY_cli_Getenv -func SKY_cli_Getenv(varname string, _arg0 *C.GoString_) (____error_code uint32) { - __arg0 := os.Getenv(varname) - copyString(__arg0, _arg0) +func SKY_cli_Getenv(varname string, _arg0 *string) (____error_code uint32) { + *_arg0 = os.Getenv(varname) return } diff --git a/lib/cgo/coin.block.go b/lib/cgo/coin.block.go index 2e6e1b75a..7e712132f 100644 --- a/lib/cgo/coin.block.go +++ b/lib/cgo/coin.block.go @@ -233,7 +233,7 @@ func SKY_coin_CreateUnspents(_bh *C.coin__BlockHeader, _tx C.Transaction__Handle return } __arg2 := coin.CreateUnspents(bh, *tx) - copyToGoSlice(reflect.ValueOf(__arg2), _arg2) + copyTocoin_UxArray(reflect.ValueOf(__arg2), _arg2) return } diff --git a/lib/cgo/coin.outputs.go b/lib/cgo/coin.outputs.go index bafc22137..207494ea7 100644 --- a/lib/cgo/coin.outputs.go +++ b/lib/cgo/coin.outputs.go @@ -124,7 +124,7 @@ func SKY_coin_UxArray_Sub(_ua *C.coin__UxArray, _other *C.coin__UxArray, _arg1 * ua := *(*coin.UxArray)(unsafe.Pointer(_ua)) other := *(*coin.UxArray)(unsafe.Pointer(_other)) __arg1 := ua.Sub(other) - copyToGoSlice(reflect.ValueOf(__arg1), _arg1) + copyTocoin_UxArray(reflect.ValueOf(__arg1), _arg1) return } @@ -133,7 +133,7 @@ func SKY_coin_UxArray_Add(_ua *C.coin__UxArray, _other *C.coin__UxArray, _arg1 * ua := *(*coin.UxArray)(unsafe.Pointer(_ua)) other := *(*coin.UxArray)(unsafe.Pointer(_other)) __arg1 := ua.Add(other) - copyToGoSlice(reflect.ValueOf(__arg1), _arg1) + copyTocoin_UxArray(reflect.ValueOf(__arg1), _arg1) return } @@ -165,7 +165,7 @@ func SKY_coin_AddressUxOuts_Flatten(_address_outs C.AddressUxOuts_Handle, _ua *C return } ux := (*address_outs).Flatten() - copyToGoSlice(reflect.ValueOf(ux), _ua) + copyTocoin_UxArray(reflect.ValueOf(ux), _ua) return } @@ -210,7 +210,7 @@ func SKY_coin_AddressUxOuts_Get(handle C.AddressUxOuts_Handle, _key *C.cipher__A key := *(*cipher.Address)(unsafe.Pointer(_key)) uxOuts, found := (*a)[key] if found { - copyToGoSlice(reflect.ValueOf(uxOuts), _uxOuts) + copyTocoin_UxArray(reflect.ValueOf(uxOuts), _uxOuts) ____error_code = SKY_OK } } else { diff --git a/lib/cgo/coin.transactions.go b/lib/cgo/coin.transactions.go index 7da0bee71..742a45bd5 100644 --- a/lib/cgo/coin.transactions.go +++ b/lib/cgo/coin.transactions.go @@ -48,17 +48,6 @@ func SKY_coin_Transaction_Copy(handle C.Transaction__Handle, handle2 *C.Transact return } -//export SKY_coin_GetTransactionObject -func SKY_coin_GetTransactionObject(handle C.Transaction__Handle, _pptx **C.coin__Transaction) (____error_code uint32) { - ptx, ok := lookupTransactionHandle(handle) - if !ok { - ____error_code = SKY_BAD_HANDLE - } else { - *_pptx = (*C.coin__Transaction)(unsafe.Pointer(ptx)) - } - return -} - //export SKY_coin_Transaction_ResetInputs func SKY_coin_Transaction_ResetInputs(handle C.Transaction__Handle, count int) (____error_code uint32) { txn, ok := lookupTransactionHandle(handle) @@ -373,6 +362,11 @@ func SKY_coin_Transaction_Serialize(handle C.Transaction__Handle, _arg0 *C.GoSli //export SKY_coin_TransactionDeserialize func SKY_coin_TransactionDeserialize(_b []byte, _arg1 *C.Transaction__Handle) (____error_code uint32) { b := *(*[]byte)(unsafe.Pointer(&_b)) + + if b == nil { + ____error_code = SKY_BAD_HANDLE + return + } __arg1, ____return_err := coin.DeserializeTransaction(b) ____error_code = libErrorCode(____return_err) if ____return_err == nil { @@ -403,17 +397,6 @@ func SKY_coin_Create_Transactions(handle *C.Transactions__Handle) (____error_cod return SKY_OK } -//export SKY_coin_GetTransactionsObject -func SKY_coin_GetTransactionsObject(handle C.Transactions__Handle, _pptx **C.coin__Transactions) (____error_code uint32) { - ptx, ok := lookupTransactionsHandle(handle) - if !ok { - ____error_code = SKY_BAD_HANDLE - } else { - *_pptx = (*C.coin__Transactions)(unsafe.Pointer(ptx)) - } - return -} - //export SKY_coin_Transactions_Length func SKY_coin_Transactions_Length(handle C.Transactions__Handle, _length *int) (____error_code uint32) { txns, ok := lookupTransactionsHandle(handle) @@ -560,7 +543,7 @@ func SKY_coin_SortTransactions(tsh C.Transactions__Handle, pFeeCalc *C.FeeCalcul } //export SKY_coin_NewSortableTransactions -func SKY_coin_NewSortableTransactions(tsh C.Transactions__Handle, pFeeCalc *C.FeeCalculator, ptsh *C.SortableTransactionResult_Handle) (____error_code uint32) { +func SKY_coin_NewSortableTransactions(tsh C.Transactions__Handle, pFeeCalc *C.FeeCalculator, ptsh *C.SortableTransactions_Handle) (____error_code uint32) { feeCalc := func(pTx *coin.Transaction) (uint64, error) { var fee C.GoUint64_ handle := registerTransactionHandle(pTx) @@ -586,7 +569,7 @@ func SKY_coin_NewSortableTransactions(tsh C.Transactions__Handle, pFeeCalc *C.Fe } //export SKY_coin_SortableTransactions_Sort -func SKY_coin_SortableTransactions_Sort(_txns C.SortableTransactionResult_Handle) (____error_code uint32) { +func SKY_coin_SortableTransactions_Sort(_txns C.SortableTransactions_Handle) (____error_code uint32) { txns, ok := lookupSortableTransactionHandle(_txns) if !ok { ____error_code = SKY_BAD_HANDLE @@ -597,7 +580,7 @@ func SKY_coin_SortableTransactions_Sort(_txns C.SortableTransactionResult_Handle } //export SKY_coin_SortableTransactions_Len -func SKY_coin_SortableTransactions_Len(_txns C.SortableTransactionResult_Handle, _arg0 *int) (____error_code uint32) { +func SKY_coin_SortableTransactions_Len(_txns C.SortableTransactions_Handle, _arg0 *int) (____error_code uint32) { txns, ok := lookupSortableTransactionHandle(_txns) if !ok { ____error_code = SKY_BAD_HANDLE @@ -609,7 +592,7 @@ func SKY_coin_SortableTransactions_Len(_txns C.SortableTransactionResult_Handle, } //export SKY_coin_SortableTransactions_Less -func SKY_coin_SortableTransactions_Less(_txns C.SortableTransactionResult_Handle, _i, _j int, _arg1 *bool) (____error_code uint32) { +func SKY_coin_SortableTransactions_Less(_txns C.SortableTransactions_Handle, _i, _j int, _arg1 *bool) (____error_code uint32) { txns, ok := lookupSortableTransactionHandle(_txns) if !ok { ____error_code = SKY_BAD_HANDLE @@ -623,7 +606,7 @@ func SKY_coin_SortableTransactions_Less(_txns C.SortableTransactionResult_Handle } //export SKY_coin_SortableTransactions_Swap -func SKY_coin_SortableTransactions_Swap(_txns C.SortableTransactionResult_Handle, _i, _j int) (____error_code uint32) { +func SKY_coin_SortableTransactions_Swap(_txns C.SortableTransactions_Handle, _i, _j int) (____error_code uint32) { txns, ok := lookupSortableTransactionHandle(_txns) if !ok { ____error_code = SKY_BAD_HANDLE @@ -671,3 +654,111 @@ func SKY_coin_VerifyInputSignatures(handle C.Transaction__Handle, _uxIn *C.coin_ return } + +//export SKY_coin_Transaction_GetLength +func SKY_coin_Transaction_GetLength(handle C.Transaction__Handle, _arg0 *uint32) (____error_code uint32) { + tx, ok := lookupTransactionHandle(handle) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + + *_arg0 = tx.Length + + return +} + +//export SKY_coin_Transaction_GetType +func SKY_coin_Transaction_GetType(handle C.Transaction__Handle, _arg0 *uint8) (____error_code uint32) { + tx, ok := lookupTransactionHandle(handle) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + + *_arg0 = tx.Type + return +} + +//export SKY_coin_Transaction_GetInnerHash +func SKY_coin_Transaction_GetInnerHash(handle C.Transaction__Handle, _arg0 *C.cipher__SHA256) (____error_code uint32) { + tx, ok := lookupTransactionHandle(handle) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + + *_arg0 = *(*C.cipher__SHA256)(unsafe.Pointer(&tx.InnerHash)) + return +} + +//export SKY_coin_Transaction_GetSigs +func SKY_coin_Transaction_GetSigs(handle C.Transaction__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + tx, ok := lookupTransactionHandle(handle) + if !ok { + ___error_code = SKY_BAD_HANDLE + return + } + + copyToGoSlice(reflect.ValueOf(tx.Sigs), _arg0) + return +} + +//export SKY_coin_Transaction_GetIn +func SKY_coin_Transaction_GetIn(handle C.Transaction__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + tx, ok := lookupTransactionHandle(handle) + if !ok { + ___error_code = SKY_BAD_HANDLE + return + } + + copyToGoSlice(reflect.ValueOf(tx.In), _arg0) + return +} + +//export SKY_coin_Transaction_GetOut +func SKY_coin_Transaction_GetOut(handle C.Transaction__Handle, _arg0 *C.GoSlice_) (___error_code uint32) { + tx, ok := lookupTransactionHandle(handle) + if !ok { + ___error_code = SKY_BAD_HANDLE + return + } + + copyToGoSlice(reflect.ValueOf(tx.Out), _arg0) + return +} + +//export SKY_coin_Transaction_SetInnerHash +func SKY_coin_Transaction_SetInnerHash(handle *C.Transaction__Handle, _sha *C.cipher__SHA256) (___error_code uint32) { + tx, ok := lookupTransactionHandle(*handle) + if !ok { + ___error_code = SKY_BAD_HANDLE + return + } + uxHash := *(*cipher.SHA256)(unsafe.Pointer(_sha)) + tx.InnerHash = uxHash + return +} + +//export SKY_coin_DeserializeTransactionHex +func SKY_coin_DeserializeTransactionHex(_s string, _arg0 *C.Transaction__Handle) (___error_code uint32) { + + arg0, err := coin.DeserializeTransactionHex(_s) + + ___error_code = libErrorCode(err) + if err == nil { + *_arg0 = registerTransactionHandle(&arg0) + } + return +} + +//export SKY_coin_GetTransactionObject +func SKY_coin_GetTransactionObject(handle C.Transaction__Handle, _pptx **C.coin__Transaction) (____error_code uint32) { + ptx, ok := lookupTransactionHandle(handle) + if !ok { + ____error_code = SKY_BAD_HANDLE + } else { + *_pptx = (*C.coin__Transaction)(unsafe.Pointer(ptx)) + } + return +} diff --git a/lib/cgo/libsky_error.go b/lib/cgo/libsky_error.go index 0cb7be00e..2b68c12f5 100644 --- a/lib/cgo/libsky_error.go +++ b/lib/cgo/libsky_error.go @@ -3,9 +3,12 @@ package main import ( "errors" + "github.com/skycoin/skycoin/src/cipher/bip44" + "github.com/skycoin/skycoin/src/transaction" "github.com/skycoin/skycoin/src/cipher" + "github.com/skycoin/skycoin/src/cipher/bip32" "github.com/skycoin/skycoin/src/cipher/encoder" "github.com/skycoin/skycoin/src/cipher/encrypt" "github.com/skycoin/skycoin/src/cli" @@ -179,6 +182,37 @@ const ( SKY_ErrReadDataLengthFailed // SKY_ErrInvalidDataLength invalid data length SKY_ErrInvalidDataLength + + // bip32 + SKY_ErrSerializedKeyWrongSize + SKY_ErrHardenedChildPublicKey + SKY_bip32_ErrInvalidChecksum + SKY_ErrDerivedInvalidPrivateKey + SKY_ErrDerivedInvalidPublicKey + SKY_ErrInvalidPrivateKeyVersion + SKY_ErrInvalidPublicKeyVersion + SKY_ErrInvalidSeedLength + SKY_ErrDeserializePrivateFromPublic + SKY_ErrInvalidKeyVersion + SKY_ErrInvalidFingerprint + SKY_ErrInvalidChildNumber + SKY_ErrInvalidPrivateKey + SKY_ErrInvalidPublicKey + SKY_ErrMaxDepthReached + // bip44 + // ErrInvalidCoinType coin_type is >= 0x80000000 + SKY_ErrInvalidCoinType + // ErrInvalidAccount account is >= 0x80000000 + SKY_ErrInvalidAccount + // bip32.path + // SKY_ErrPathNoMaster HD wallet path does not start with m + SKY_ErrPathNoMaster + // SKY_ErrPathChildMaster HD wallet path contains m in a child node + SKY_ErrPathChildMaster + // SKY_ErrPathNodeNotNumber HD wallet path node is not a valid uint32 number + SKY_ErrPathNodeNotNumber + // SKY_ErrPathNodeNumberTooLarge HD wallet path node is >= 2^31 + SKY_ErrPathNodeNumberTooLarge ) // Error codes defined in cli package @@ -591,6 +625,28 @@ var ( visor.ErrDuplicateUxOuts: SKY_ErrDuplicateUxOuts, // params params.ErrInvalidDecimals: SKY_ErrInvalidDecimals, + // bip32 + bip32.ErrSerializedKeyWrongSize: SKY_ErrSerializedKeyWrongSize, + bip32.ErrHardenedChildPublicKey: SKY_ErrHardenedChildPublicKey, + bip32.ErrInvalidChecksum: SKY_bip32_ErrInvalidChecksum, + bip32.ErrDerivedInvalidPrivateKey: SKY_ErrDerivedInvalidPrivateKey, + bip32.ErrDerivedInvalidPublicKey: SKY_ErrDerivedInvalidPublicKey, + bip32.ErrInvalidPrivateKeyVersion: SKY_ErrInvalidPrivateKeyVersion, + bip32.ErrInvalidPublicKeyVersion: SKY_ErrInvalidPublicKeyVersion, + bip32.ErrInvalidSeedLength: SKY_ErrInvalidSeedLength, + bip32.ErrDeserializePrivateFromPublic: SKY_ErrDeserializePrivateFromPublic, + bip32.ErrInvalidKeyVersion: SKY_ErrInvalidKeyVersion, + bip32.ErrInvalidFingerprint: SKY_ErrInvalidFingerprint, + bip32.ErrInvalidChildNumber: SKY_ErrInvalidChildNumber, + bip32.ErrInvalidPrivateKey: SKY_ErrInvalidPrivateKey, + bip32.ErrInvalidPublicKey: SKY_ErrInvalidPublicKey, + bip32.ErrMaxDepthReached: SKY_ErrMaxDepthReached, + bip44.ErrInvalidCoinType: SKY_ErrInvalidCoinType, + bip44.ErrInvalidAccount: SKY_ErrInvalidAccount, + bip32.ErrPathNoMaster: SKY_ErrPathNoMaster, + bip32.ErrPathChildMaster: SKY_ErrPathChildMaster, + bip32.ErrPathNodeNotNumber: SKY_ErrPathNodeNotNumber, + bip32.ErrPathNodeNumberTooLarge: SKY_ErrPathNodeNumberTooLarge, } ) diff --git a/lib/cgo/libsky_handle.go b/lib/cgo/libsky_handle.go index 0ff842a03..de8157ba5 100644 --- a/lib/cgo/libsky_handle.go +++ b/lib/cgo/libsky_handle.go @@ -16,8 +16,11 @@ import ( "github.com/spf13/cobra" "github.com/skycoin/skycoin/src/api" + "github.com/skycoin/skycoin/src/cipher/bip32" + "github.com/skycoin/skycoin/src/cipher/bip44" "github.com/skycoin/skycoin/src/cli" "github.com/skycoin/skycoin/src/coin" + "github.com/skycoin/skycoin/src/params" "github.com/skycoin/skycoin/src/readable" "github.com/skycoin/skycoin/src/wallet" ) @@ -65,14 +68,42 @@ func lookupWalletHandle(handle C.Wallet__Handle) (*wallet.Wallet, bool) { return nil, false } -func registerReadableWalletHandle(obj *wallet.ReadableWallet) C.ReadableWallet__Handle { +func registerCollectionWalletHandle(obj *wallet.CollectionWallet) C.CollectionWallet__Handle { + return (C.Wallet__Handle)(registerHandle(obj)) +} + +func lookupCollectionWalletHandle(handle C.Wallet__Handle) (*wallet.CollectionWallet, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*wallet.CollectionWallet); isOK { + return obj, true + } + } + return nil, false +} + +func registerMetaWalletHandle(obj *wallet.Meta) C.MetaWallet__Handle { + return (C.MetaWallet__Handle)(registerHandle(obj)) +} + +func lookupMetaWalletHandle(handle C.MetaWallet__Handle) (*wallet.Meta, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*wallet.Meta); isOK { + return obj, true + } + } + return nil, false +} + +func registerReadableWalletHandle(obj *wallet.Readable) C.ReadableWallet__Handle { return (C.ReadableWallet__Handle)(registerHandle(obj)) } -func lookupReadableWalletHandle(handle C.ReadableWallet__Handle) (*wallet.ReadableWallet, bool) { +func lookupReadableWalletHandle(handle C.ReadableWallet__Handle) (*wallet.Readable, bool) { obj, ok := lookupHandle(C.Handle(handle)) if ok { - if obj, isOK := (obj).(*wallet.ReadableWallet); isOK { + if obj, isOK := (obj).(*wallet.Readable); isOK { return obj, true } } @@ -359,11 +390,11 @@ func lookupTransactionResultHandle(handle C.TransactionResult_Handle) (*cli.TxnR return nil, false } -func registerSortableTransactiontHandle(obj *coin.SortableTransactions) C.SortableTransactionResult_Handle { - return (C.SortableTransactionResult_Handle)(registerHandle(obj)) +func registerSortableTransactiontHandle(obj *coin.SortableTransactions) C.SortableTransactions_Handle { + return (C.SortableTransactions_Handle)(registerHandle(obj)) } -func lookupSortableTransactionHandle(handle C.SortableTransactionResult_Handle) (*coin.SortableTransactions, bool) { +func lookupSortableTransactionHandle(handle C.SortableTransactions_Handle) (*coin.SortableTransactions, bool) { obj, ok := lookupHandle(C.Handle(handle)) if ok { if obj, isOK := (obj).(*coin.SortableTransactions); isOK { @@ -490,3 +521,143 @@ func lookupBlockHeaderHandle(handle C.BlockHeader__Handle) (*coin.BlockHeader, b } return nil, false } + +func registerWalletSeedResponseHandle(obj *api.WalletSeedResponse) C.WalletSeedResponse__Handle { + return (C.WalletResponse__Handle)(registerHandle(obj)) +} + +func lookupWalletSeedResponseHandle(handle C.WalletSeedResponse__Handle) (*api.WalletSeedResponse, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*api.WalletSeedResponse); isOK { + return obj, true + } + } + return nil, false +} + +func registerDistributionHandle(obj *params.Distribution) C.Distribution__Handle { + return (C.Distribution__Handle)(registerHandle(obj)) +} + +func lookupDistributionHandle(handle C.Distribution__Handle) (*params.Distribution, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*params.Distribution); isOK { + return obj, true + } + } + return nil, false +} + +func registerCreateWalletOptionsHandle(obj *api.CreateWalletOptions) C.CreateWalletOptions__Handle { + return (C.CreateWalletOptions__Handle)(registerHandle(obj)) +} + +func lookupCreateWalletOptionsHandle(handle C.CreateWalletOptions__Handle) (*api.CreateWalletOptions, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*api.CreateWalletOptions); isOK { + return obj, true + } + } + return nil, false +} + +func registerWalletRecoverRequestHandle(obj *api.WalletRecoverRequest) C.WalletRecoverRequest__Handle { + return (C.CreateWalletOptions__Handle)(registerHandle(obj)) +} + +func lookupWalletRecoverRequestHandle(handle C.WalletRecoverRequest__Handle) (*api.WalletRecoverRequest, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*api.WalletRecoverRequest); isOK { + return obj, true + } + } + return nil, false +} + +func registerPublicKeyHandle(obj *bip32.PublicKey) C.PublicKey__Handle { + return (C.PublicKey__Handle)(registerHandle(obj)) +} + +func lookupPublicKeyHandle(handle C.PublicKey__Handle) (*bip32.PublicKey, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*bip32.PublicKey); isOK { + return obj, true + } + } + return nil, false +} + +func registerPrivateKeyHandle(obj *bip32.PrivateKey) C.PrivateKey__Handle { + return (C.PublicKey__Handle)(registerHandle(obj)) +} + +func lookupPrivateKeyHandle(handle C.PrivateKey__Handle) (*bip32.PrivateKey, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*bip32.PrivateKey); isOK { + return obj, true + } + } + return nil, false +} + +func registerPathHandle(obj *bip32.Path) C.Path__Handle { + return (C.Path__Handle)(registerHandle(obj)) +} + +func lookupPathHandle(handle C.Path__Handle) (*bip32.Path, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*bip32.Path); isOK { + return obj, true + } + } + return nil, false +} + +func registerCoinHandle(obj *bip44.Coin) C.Coin__Handle { + return (C.Coin__Handle)(registerHandle(obj)) +} + +func lookupCoinHandle(handle C.Coin__Handle) (*bip44.Coin, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*bip44.Coin); isOK { + return obj, true + } + } + return nil, false +} + +func registerAccountHandle(obj *bip44.Account) C.Account__Handle { + return (C.Account__Handle)(registerHandle(obj)) +} + +func lookupAccountHandle(handle C.Account__Handle) (*bip44.Account, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*bip44.Account); isOK { + return obj, true + } + } + return nil, false +} + +func registerGetOutputserHandle(obj *cli.GetOutputser) C.GetOutputser__Handle { + return (C.Account__Handle)(registerHandle(obj)) +} + +func lookupGetOutputserHandle(handle C.GetOutputser__Handle) (*cli.GetOutputser, bool) { + obj, ok := lookupHandle(C.Handle(handle)) + if ok { + if obj, isOK := (obj).(*cli.GetOutputser); isOK { + return obj, true + } + } + return nil, false +} diff --git a/lib/cgo/libsky_handle_helper.go b/lib/cgo/libsky_handle_helper.go index 8bb40e971..a89e27a15 100644 --- a/lib/cgo/libsky_handle_helper.go +++ b/lib/cgo/libsky_handle_helper.go @@ -13,8 +13,6 @@ import "C" import ( "encoding/json" "path/filepath" - "sort" - "unsafe" api "github.com/skycoin/skycoin/src/api" "github.com/skycoin/skycoin/src/daemon" @@ -121,48 +119,8 @@ func SKY_Handle_Connections_GetCount(handle C.Handle, return SKY_BAD_HANDLE } -//export SKY_Handle_Strings_GetCount -func SKY_Handle_Strings_GetCount(handle C.Strings__Handle, - count *uint32) uint32 { - obj, ok := lookupHandle(C.Handle(handle)) - if ok { - if obj, isOK := (obj).([]string); isOK { - *count = uint32(len(obj)) - return SKY_OK - } - } - return SKY_BAD_HANDLE -} - -//export SKY_Handle_Strings_Sort -func SKY_Handle_Strings_Sort(handle C.Strings__Handle) uint32 { - obj, ok := lookupHandle(C.Handle(handle)) - if ok { - if obj, isOK := (obj).([]string); isOK { - sort.Strings(obj) - return SKY_OK - } - } - return SKY_BAD_HANDLE -} - -//export SKY_Handle_Strings_GetAt -func SKY_Handle_Strings_GetAt(handle C.Strings__Handle, - index int, - str *C.GoString_) uint32 { - obj, ok := lookupHandle(C.Handle(handle)) - if ok { - if obj, isOK := (obj).([]string); isOK { - copyString(obj[index], str) - return SKY_OK - } - } - return SKY_BAD_HANDLE -} - //export SKY_api_Handle_Client_GetWalletDir -func SKY_api_Handle_Client_GetWalletDir(handle C.Client__Handle, - walletDir *C.GoString_) uint32 { +func SKY_api_Handle_Client_GetWalletDir(handle C.Client__Handle, walletDir *C.GoString_) uint32 { client, ok := lookupClientHandle(handle) if ok { wf, err := client.WalletFolderName() @@ -216,28 +174,6 @@ func SKY_api_Handle_Client_GetWalletFullPath( return SKY_BAD_HANDLE } -//export SKY_api_Handle_GetWalletMeta -func SKY_api_Handle_GetWalletMeta(handle C.Wallet__Handle, - gomap *C.GoStringMap_) uint32 { - w, ok := lookupWalletHandle(handle) - if ok { - copyToStringMap(w.Meta, gomap) - return SKY_OK - } - return SKY_BAD_HANDLE -} - -//export SKY_api_Handle_GetWalletEntriesCount -func SKY_api_Handle_GetWalletEntriesCount(handle C.Wallet__Handle, - count *uint32) uint32 { - w, ok := lookupWalletHandle(handle) - if ok { - *count = uint32(len(w.Entries)) - return SKY_OK - } - return SKY_BAD_HANDLE -} - //export SKY_api_Handle_Client_GetWalletResponseEntriesCount func SKY_api_Handle_Client_GetWalletResponseEntriesCount( handle C.WalletResponse__Handle, @@ -250,22 +186,6 @@ func SKY_api_Handle_Client_GetWalletResponseEntriesCount( return SKY_BAD_HANDLE } -//export SKY_api_Handle_WalletGetEntry -func SKY_api_Handle_WalletGetEntry(handle C.Wallet__Handle, - index uint32, - address *C.cipher__Address, - pubkey *C.cipher__PubKey) uint32 { - w, ok := lookupWalletHandle(handle) - if ok { - if index < uint32(len(w.Entries)) { - *address = *(*C.cipher__Address)(unsafe.Pointer(&w.Entries[index].Address)) - *pubkey = *(*C.cipher__PubKey)(unsafe.Pointer(&w.Entries[index].Public)) - return SKY_OK - } - } - return SKY_BAD_HANDLE -} - //export SKY_api_Handle_WalletResponseGetEntry func SKY_api_Handle_WalletResponseGetEntry(handle C.WalletResponse__Handle, index uint32, @@ -294,18 +214,6 @@ func SKY_api_Handle_WalletResponseIsEncrypted( return SKY_BAD_HANDLE } -//export SKY_api_Handle_WalletResponseGetCryptoType -func SKY_api_Handle_WalletResponseGetCryptoType( - handle C.WalletResponse__Handle, - cryptoType *C.GoString_) uint32 { - w, ok := lookupWalletResponseHandle(handle) - if ok { - copyString(w.Meta.CryptoType, cryptoType) - return SKY_OK - } - return SKY_BAD_HANDLE -} - //export SKY_api_Handle_WalletsResponseGetCount func SKY_api_Handle_WalletsResponseGetCount( handle C.Wallets__Handle, @@ -348,22 +256,22 @@ func SKY_api_Handle_GetWalletFolderAddress( } //export SKY_api_Handle_GetWalletSeed -func SKY_api_Handle_GetWalletSeed(handle C.Wallet__Handle, +func SKY_api_Handle_GetWalletSeed(handle C.MetaWallet__Handle, seed *C.GoString_) uint32 { - w, ok := lookupWalletHandle(handle) + w, ok := lookupMetaWalletHandle(handle) if ok { - copyString(w.Meta["seed"], seed) + copyString(w.Seed(), seed) return SKY_OK } return SKY_BAD_HANDLE } //export SKY_api_Handle_GetWalletLastSeed -func SKY_api_Handle_GetWalletLastSeed(handle C.Wallet__Handle, +func SKY_api_Handle_GetWalletLastSeed(handle C.MetaWallet__Handle, lastSeed *C.GoString_) uint32 { - w, ok := lookupWalletHandle(handle) + w, ok := lookupMetaWalletHandle(handle) if ok { - copyString(w.Meta["lastSeed"], lastSeed) + copyString(w.LastSeed(), lastSeed) return SKY_OK } return SKY_BAD_HANDLE diff --git a/lib/cgo/libsky_mem.go b/lib/cgo/libsky_mem.go index 66c847542..cb84945fc 100644 --- a/lib/cgo/libsky_mem.go +++ b/lib/cgo/libsky_mem.go @@ -129,3 +129,29 @@ func copyToGoSlice(src reflect.Value, dest *C.GoSlice_) { func copyToStringMap(gomap map[string]string, dest *C.GoStringMap_) { *dest = (C.GoStringMap_)(registerHandle(gomap)) } + +func copyTocoin_UxArray(src reflect.Value, dest *C.coin__UxArray) { + srcLen := src.Len() + if srcLen == 0 { + dest.len = 0 + return + } + srcAddr, elemSize := getBufferData(src) + if dest.cap == 0 { + dest.data = C.malloc(C.size_t(srcLen) * elemSize) + dest.cap = C.GoInt_(srcLen) + } + n, overflow := srcLen, srcLen > int(dest.cap) + if overflow { + n = int(dest.cap) + } + result := C.memcpy(dest.data, srcAddr, C.size_t(n)*elemSize) + if result != nil { + // Do not modify slice metadata until memory is actually copied + if overflow { + dest.len = dest.cap - C.GoInt_(srcLen) + } else { + dest.len = C.GoInt_(srcLen) + } + } +} diff --git a/lib/cgo/params.distribution.go b/lib/cgo/params.distribution.go index 90ef24c09..fc29f1906 100644 --- a/lib/cgo/params.distribution.go +++ b/lib/cgo/params.distribution.go @@ -3,7 +3,7 @@ package main import ( "reflect" - params "github.com/skycoin/skycoin/src/params" + "github.com/skycoin/skycoin/src/params" ) /* @@ -15,20 +15,231 @@ import ( */ import "C" -//export SKY_params_GetDistributionAddresses -func SKY_params_GetDistributionAddresses(_arg0 *C.GoSlice_) { - __arg0 := params.GetDistributionAddresses() - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) +//export SKY_params_Distribution_GetMaxCoinSupply +func SKY_params_Distribution_GetMaxCoinSupply(_d C.Distribution__Handle, _arg0 *uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = d.MaxCoinSupply + return } -//export SKY_params_GetUnlockedDistributionAddresses -func SKY_params_GetUnlockedDistributionAddresses(_arg0 *C.GoSlice_) { - __arg0 := params.GetUnlockedDistributionAddresses() - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) +// nolint megacheck +//export SKY_params_Distribution_SetMaxCoinSupply +func SKY_params_Distribution_SetMaxCoinSupply(_d C.Distribution__Handle, _arg0 uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + d.MaxCoinSupply = _arg0 + _d = registerDistributionHandle(d) + return } -//export SKY_params_GetLockedDistributionAddresses -func SKY_params_GetLockedDistributionAddresses(_arg0 *C.GoSlice_) { - __arg0 := params.GetLockedDistributionAddresses() - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) +//export SKY_params_Distribution_GetInitialUnlockedCount +func SKY_params_Distribution_GetInitialUnlockedCount(_d C.Distribution__Handle, _arg0 *uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = d.InitialUnlockedCount + return +} + +// nolint megacheck +//export SKY_params_Distribution_SetInitialUnlockedCount +func SKY_params_Distribution_SetInitialUnlockedCount(_d C.Distribution__Handle, _arg0 uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + d.InitialUnlockedCount = _arg0 + _d = registerDistributionHandle(d) + return +} + +//export SKY_params_Distribution_GetUnlockAddressRate +func SKY_params_Distribution_GetUnlockAddressRate(_d C.Distribution__Handle, _arg0 *uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = d.UnlockAddressRate + return +} + +// nolint megacheck +//export SKY_params_Distribution_SetUnlockAddressRate +func SKY_params_Distribution_SetUnlockAddressRate(_d C.Distribution__Handle, _arg0 uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + d.UnlockAddressRate = _arg0 + _d = registerDistributionHandle(d) + return +} + +//export SKY_params_Distribution_GetUnlockTimeInterval +func SKY_params_Distribution_GetUnlockTimeInterval(_d C.Distribution__Handle, _arg0 *uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = d.UnlockTimeInterval + return +} + +// nolint megacheck +//export SKY_params_Distribution_SetUnlockTimeInterval +func SKY_params_Distribution_SetUnlockTimeInterval(_d C.Distribution__Handle, _arg0 uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + d.UnlockTimeInterval = _arg0 + _d = registerDistributionHandle(d) + return +} + +//export SKY_params_Distribution_GetAddresses +func SKY_params_Distribution_GetAddresses(_d C.Distribution__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + arg0 := d.Addresses + copyToGoSlice(reflect.ValueOf(arg0), _arg0) + return +} + +// nolint megacheck +//export SKY_params_Distribution_SetAddresses +func SKY_params_Distribution_SetAddresses(_d C.Distribution__Handle, _arg0 []string) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + d.Addresses = _arg0 + _d = registerDistributionHandle(d) + return +} + +//export SKY_params_Distribution_Validate +func SKY_params_Distribution_Validate(_d C.Distribution__Handle) (____error_code uint32) { + + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + __return_err := d.Validate() + ____error_code = libErrorCode(__return_err) + return + +} + +//export SKY_params_Distribution_AddressInitialBalance +func SKY_params_Distribution_AddressInitialBalance(_d C.Distribution__Handle, _arg0 *uint64) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = d.AddressInitialBalance() + return +} + +//export SKY_params_Distribution_UnlockedAddresses +func SKY_params_Distribution_UnlockedAddresses(_d C.Distribution__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + + arg0 := d.UnlockedAddresses() + copyToGoSlice(reflect.ValueOf(arg0), _arg0) + + return +} + +//export SKY_params_Distribution_LockedAddresses +func SKY_params_Distribution_LockedAddresses(_d C.Distribution__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + + arg0 := d.LockedAddresses() + copyToGoSlice(reflect.ValueOf(arg0), _arg0) + return +} + +//export SKY_params_Distribution_AddressesDecoded +func SKY_params_Distribution_AddressesDecoded(_d C.Distribution__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + arg0 := d.AddressesDecoded() + copyToGoSlice(reflect.ValueOf(arg0), _arg0) + return +} + +//export SKY_params_Distribution_UnlockedAddressesDecoded +func SKY_params_Distribution_UnlockedAddressesDecoded(_d C.Distribution__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + arg0 := d.UnlockedAddressesDecoded() + copyToGoSlice(reflect.ValueOf(arg0), _arg0) + return +} + +//export SKY_params_Distribution_LockedAddressesDecoded +func SKY_params_Distribution_LockedAddressesDecoded(_d C.Distribution__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { + d, ok := lookupDistributionHandle(_d) + if !ok { + ____error_code = SKY_BAD_HANDLE + return + } + arg0 := d.LockedAddressesDecoded() + copyToGoSlice(reflect.ValueOf(arg0), _arg0) + return +} + +//export SKY_params_Distribution_GetMainNetDistribution +func SKY_params_Distribution_GetMainNetDistribution(handle *C.Distribution__Handle) (____error_code uint32) { + d := params.Distribution{} + d.MaxCoinSupply = params.MainNetDistribution.MaxCoinSupply + d.InitialUnlockedCount = params.MainNetDistribution.InitialUnlockedCount + d.UnlockAddressRate = params.MainNetDistribution.UnlockAddressRate + d.UnlockTimeInterval = params.MainNetDistribution.UnlockTimeInterval + d.Addresses = make([]string, 0) + d.Addresses = append(d.Addresses, params.MainNetDistribution.Addresses...) + *handle = registerDistributionHandle(&d) + return +} + +//export SKY_params_NewDistribution +func SKY_params_NewDistribution(_d *C.Distribution__Handle) (____error_code uint32) { + d := params.Distribution{} + *_d = registerDistributionHandle(&d) + return } diff --git a/lib/cgo/tests/check_cipher.address.c b/lib/cgo/tests/check_cipher.address.c index d49c22539..3929d8618 100644 --- a/lib/cgo/tests/check_cipher.address.c +++ b/lib/cgo/tests/check_cipher.address.c @@ -1,140 +1,17 @@ +#include +#include + +#include +#include + #include "libskycoin.h" +#include "skyassert.h" #include "skyerrors.h" #include "skystring.h" #include "skytest.h" -#include -#include -#include -#include #define SKYCOIN_ADDRESS_VALID "2GgFvqoyk9RjwVzj8tqfcXVXB4orBwoc9qv" -START_TEST(TestDecodeBase58Address) -{ - GoString strAddr = {SKYCOIN_ADDRESS_VALID, 35}; - cipher__Address addr; - GoUint32 err = SKY_cipher_DecodeBase58Address(strAddr, &addr); - ck_assert_int_eq(err, SKY_OK); - GoUint8 buff[1024]; - char tempStr[50]; - int errorcode; - - // preceding whitespace is invalid - strcpy(tempStr, " "); - strcat(tempStr, SKYCOIN_ADDRESS_VALID); - strAddr.p = tempStr; - strAddr.n = strlen(tempStr); - errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); - ck_assert_msg(errorcode == SKY_ERROR, "preceding whitespace is invalid"); - - // preceding zeroes are invalid - strcpy(tempStr, "000"); - strcat(tempStr, SKYCOIN_ADDRESS_VALID); - strAddr.p = tempStr; - strAddr.n = strlen(tempStr); - errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); - ck_assert_msg(errorcode == SKY_ERROR, "leading zeroes prefix are invalid"); - - // trailing whitespace is invalid - strcpy(tempStr, SKYCOIN_ADDRESS_VALID); - strcat(tempStr, " "); - strAddr.p = tempStr; - strAddr.n = strlen(tempStr); - errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); - ck_assert_msg(errorcode == SKY_ERROR, "trailing whitespace is invalid"); - - // trailing zeroes are invalid - strcpy(tempStr, SKYCOIN_ADDRESS_VALID); - strcat(tempStr, "000"); - strAddr.p = tempStr; - strAddr.n = strlen(tempStr); - errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); - ck_assert_msg(errorcode == SKY_ERROR, "trailing zeroes suffix are invalid"); - - cipher__PubKey p; - cipher__SecKey s; - errorcode = SKY_cipher_GenerateKeyPair(&p, &s); - ck_assert(errorcode == SKY_OK); - cipher__Address a; - errorcode = SKY_cipher_AddressFromPubKey(&p, &a); - ck_assert(errorcode == SKY_OK); - GoSlice b; - coin__UxArray Cub; - Cub.data = buff; - Cub.len = 0; - Cub.cap = sizeof(buff); - errorcode = SKY_cipher_Address_Bytes(&addr, &Cub); - ck_assert_msg(errorcode == SKY_OK, "Fail SKY_cipher_Address_Bytes"); - b.cap = Cub.cap; - b.data = Cub.data; - b.len = Cub.len; - - int len_b = b.len; - char bufferHead[1024]; - GoString_ h = {bufferHead, 0}; - b.len = (GoInt)(len_b / 2); - errorcode = SKY_base58_Hex2Base58(b, &h); - ck_assert(errorcode == SKY_OK); - char bufferHeadTmp[1024]; - GoString tmph = {bufferHeadTmp, 0}; - tmph.n = h.n; - tmph.p = h.p; - errorcode = SKY_cipher_DecodeBase58Address(tmph, &addr); - ck_assert_msg(errorcode == SKY_ErrAddressInvalidLength, "Fail %X", errorcode); - b.len = len_b; - errorcode = SKY_base58_Hex2Base58(b, &h); - ck_assert(errorcode == SKY_OK); - tmph.n = h.n; - tmph.p = h.p; - errorcode = SKY_cipher_DecodeBase58Address(tmph, &addr); - ck_assert_msg(errorcode == SKY_OK, "Fail %X", errorcode); -} -END_TEST - -START_TEST(TestAddressFromBytes) -{ - cipher__Address addr, addr2; - cipher__SecKey sk; - cipher__PubKey pk; - GoSlice bytes; - GoSlice_ tempBytes; - GoUint8 buff[1024]; - GoUint32 err = SKY_cipher_GenerateKeyPair(&pk, &sk); - ck_assert(err == SKY_OK); - SKY_cipher_AddressFromPubKey(&pk, &addr); - - tempBytes.data = buff; - tempBytes.len = 0; - tempBytes.cap = sizeof(buff); - - SKY_cipher_Address_Bytes(&addr, &tempBytes); - ck_assert_msg(tempBytes.len > 0, "address bytes written"); - copyGoSlice_toGoSlice(&bytes, &tempBytes, tempBytes.len); - err = SKY_cipher_AddressFromBytes(bytes, &addr2); - ck_assert_msg(err == SKY_OK, "convert bytes to SKY address"); - - ck_assert_msg(isAddressEq(&addr, &addr2), "Not equal Address"); - - int bytes_len = bytes.len; - - bytes.len = bytes.len - 2; - ck_assert_msg(SKY_cipher_AddressFromBytes(bytes, &addr2) == - SKY_ErrAddressInvalidLength, - "no SKY address due to short bytes length"); - - bytes.len = bytes_len; - ((char*)bytes.data)[bytes.len - 1] = '2'; - err = SKY_cipher_AddressFromBytes(bytes, &addr2); - ck_assert_msg(err == SKY_ErrAddressInvalidChecksum, - "no SKY address due to corrupted bytes %X", err); - - addr.Version = 2; - SKY_cipher_Address_Bytes(&addr, &tempBytes); - copyGoSlice_toGoSlice(&bytes, &tempBytes, tempBytes.len); - err = SKY_cipher_AddressFromBytes(bytes, &addr2); - ck_assert_msg(err == SKY_ErrAddressInvalidVersion, "Invalid version"); -} -END_TEST START_TEST(TestAddressRoundtrip) { @@ -147,7 +24,7 @@ START_TEST(TestAddressRoundtrip) error = SKY_cipher_AddressFromPubKey(&p, &a); ck_assert_int_eq(error, SKY_OK); unsigned char buffera_bytes[1024]; - coin__UxArray a_bytes = {buffera_bytes, 0, 1024}; + GoSlice_ a_bytes = {buffera_bytes, 0, 1024}; error = SKY_cipher_Address_Bytes(&a, &a_bytes); ck_assert_int_eq(error, SKY_OK); cipher__Address a2; @@ -163,35 +40,6 @@ START_TEST(TestAddressRoundtrip) } END_TEST -START_TEST(TestAddressVerify) -{ - cipher__PubKey pubkey; - cipher__SecKey seckey; - cipher__PubKey pubkey2; - cipher__SecKey seckey2; - cipher__Address addr; - - SKY_cipher_GenerateKeyPair(&pubkey, &seckey); - SKY_cipher_AddressFromPubKey(&pubkey, &addr); - - // Valid pubkey+address - ck_assert_msg(SKY_cipher_Address_Verify(&addr, &pubkey) == SKY_OK, - "Valid pubkey + address"); - - SKY_cipher_GenerateKeyPair(&pubkey, &seckey2); - // Invalid pubkey - ck_assert_msg(SKY_cipher_Address_Verify(&addr, &pubkey) == - SKY_ErrAddressInvalidPubKey, - " Invalid pubkey"); - - // Bad version - addr.Version = 0x01; - ck_assert_msg(SKY_cipher_Address_Verify(&addr, &pubkey) == - SKY_ErrAddressInvalidVersion, - " Bad version"); -} -END_TEST - START_TEST(TestAddressString) { cipher__PubKey pk; @@ -252,27 +100,82 @@ START_TEST(TestAddressBulk) } END_TEST -START_TEST(TestAddressNull) +START_TEST(TestDecodeBase58Address) { - cipher__Address a; - memset(&a, 0, sizeof(cipher__Address)); - GoUint32 result; - GoUint8 isNull; - result = SKY_cipher_Address_Null(&a, &isNull); - ck_assert_msg(result == SKY_OK, "SKY_cipher_Address_Null"); - ck_assert(isNull == 1); + GoString strAddr = {SKYCOIN_ADDRESS_VALID, 35}; + cipher__Address addr; + GoUint32 err = SKY_cipher_DecodeBase58Address(strAddr, &addr); + ck_assert_int_eq(err, SKY_OK); + GoUint8 buff[1024]; + char tempStr[50]; + int errorcode; + + // preceding whitespace is invalid + strcpy(tempStr, " "); + strcat(tempStr, SKYCOIN_ADDRESS_VALID); + strAddr.p = tempStr; + strAddr.n = strlen(tempStr); + errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); + ck_assert_msg(errorcode == SKY_ERROR, "preceding whitespace is invalid"); + + // preceding zeroes are invalid + strcpy(tempStr, "000"); + strcat(tempStr, SKYCOIN_ADDRESS_VALID); + strAddr.p = tempStr; + strAddr.n = strlen(tempStr); + errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); + ck_assert_msg(errorcode == SKY_ERROR, "leading zeroes prefix are invalid"); + + // trailing whitespace is invalid + strcpy(tempStr, SKYCOIN_ADDRESS_VALID); + strcat(tempStr, " "); + strAddr.p = tempStr; + strAddr.n = strlen(tempStr); + errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); + ck_assert_msg(errorcode == SKY_ERROR, "trailing whitespace is invalid"); + + // trailing zeroes are invalid + strcpy(tempStr, SKYCOIN_ADDRESS_VALID); + strcat(tempStr, "000"); + strAddr.p = tempStr; + strAddr.n = strlen(tempStr); + errorcode = SKY_cipher_DecodeBase58Address(strAddr, &addr); + ck_assert_msg(errorcode == SKY_ERROR, "trailing zeroes suffix are invalid"); cipher__PubKey p; cipher__SecKey s; + errorcode = SKY_cipher_GenerateKeyPair(&p, &s); + ck_assert(errorcode == SKY_OK); + cipher__Address a; + errorcode = SKY_cipher_AddressFromPubKey(&p, &a); + ck_assert(errorcode == SKY_OK); + GoSlice b; + GoSlice_ Cub = {buff, 0, 1024}; + errorcode = SKY_cipher_Address_Bytes(&addr, &Cub); + ck_assert_msg(errorcode == SKY_OK, "Fail SKY_cipher_Address_Bytes"); + b.cap = Cub.cap; + b.data = Cub.data; + b.len = Cub.len; - result = SKY_cipher_GenerateKeyPair(&p, &s); - ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); - - result = SKY_cipher_AddressFromPubKey(&p, &a); - ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); - result = SKY_cipher_Address_Null(&a, &isNull); - ck_assert_msg(result == SKY_OK, "SKY_cipher_Address_Null"); - ck_assert(isNull == 0); + int len_b = b.len; + char bufferHead[1024]; + GoString_ h = {bufferHead, 0}; + b.len = (GoInt)(len_b / 2); + errorcode = SKY_base58_Hex2Base58(b, &h); + ck_assert(errorcode == SKY_OK); + char bufferHeadTmp[1024]; + GoString tmph = {bufferHeadTmp, 0}; + tmph.n = h.n; + tmph.p = h.p; + errorcode = SKY_cipher_DecodeBase58Address(tmph, &addr); + ck_assert_msg(errorcode == SKY_ErrAddressInvalidLength, "Fail %X", errorcode); + b.len = len_b; + errorcode = SKY_base58_Hex2Base58(b, &h); + ck_assert(errorcode == SKY_OK); + tmph.n = h.n; + tmph.p = h.p; + errorcode = SKY_cipher_DecodeBase58Address(tmph, &addr); + ck_assert_msg(errorcode == SKY_OK, "Fail %X", errorcode); } END_TEST @@ -295,22 +198,18 @@ START_TEST(TestAddressFromSecKey) END_TEST // define test suite and cases -Suite* cipher_address(void) +Suite* check_cipher_address(void) { - Suite* s = suite_create("Load cipher.address"); + Suite* s = suite_create("Load check_cipher_address.address"); TCase* tc; - tc = tcase_create("cipher.address"); + tc = tcase_create("check_cipher.address"); tcase_add_checked_fixture(tc, setup, teardown); - tcase_add_test(tc, TestDecodeBase58Address); - tcase_add_test(tc, TestAddressFromBytes); tcase_add_test(tc, TestAddressRoundtrip); - tcase_add_test(tc, TestAddressVerify); tcase_add_test(tc, TestAddressString); tcase_add_test(tc, TestAddressBulk); - tcase_add_test(tc, TestAddressNull); - suite_add_tcase(s, tc); - tcase_set_timeout(tc, 150); + tcase_add_test(tc, TestAddressFromSecKey); + tcase_add_test(tc, TestDecodeBase58Address); return s; -} \ No newline at end of file +} diff --git a/lib/cgo/tests/check_cipher.address.common.c b/lib/cgo/tests/check_cipher.address.common.c new file mode 100644 index 000000000..6545486be --- /dev/null +++ b/lib/cgo/tests/check_cipher.address.common.c @@ -0,0 +1,125 @@ +#include "libskycoin.h" +#include "skyerrors.h" +#include "skystring.h" +#include "skytest.h" +#include +#include +#include +#include + +#define SKYCOIN_ADDRESS_VALID "2GgFvqoyk9RjwVzj8tqfcXVXB4orBwoc9qv" + +START_TEST(TestAddressVerify) +{ + cipher__PubKey pubkey; + cipher__SecKey seckey; + cipher__PubKey pubkey2; + cipher__SecKey seckey2; + cipher__Address addr; + + SKY_cipher_GenerateKeyPair(&pubkey, &seckey); + SKY_cipher_AddressFromPubKey(&pubkey, &addr); + + // Valid pubkey+address + ck_assert_msg(SKY_cipher_Address_Verify(&addr, &pubkey) == SKY_OK, + "Valid pubkey + address"); + + SKY_cipher_GenerateKeyPair(&pubkey, &seckey2); + // Invalid pubkey + ck_assert_msg(SKY_cipher_Address_Verify(&addr, &pubkey) == + SKY_ErrAddressInvalidPubKey, + " Invalid pubkey"); + + // Bad version + addr.Version = 0x01; + ck_assert_msg(SKY_cipher_Address_Verify(&addr, &pubkey) == + SKY_ErrAddressInvalidVersion, + " Bad version"); +} +END_TEST + +START_TEST(TestAddressNull) +{ + cipher__Address a; + memset(&a, 0, sizeof(cipher__Address)); + GoUint32 result; + GoUint8 isNull; + result = SKY_cipher_Address_Null(&a, &isNull); + ck_assert_msg(result == SKY_OK, "SKY_cipher_Address_Null"); + ck_assert(isNull == 1); + + cipher__PubKey p; + cipher__SecKey s; + + result = SKY_cipher_GenerateKeyPair(&p, &s); + ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); + + result = SKY_cipher_AddressFromPubKey(&p, &a); + ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); + result = SKY_cipher_Address_Null(&a, &isNull); + ck_assert_msg(result == SKY_OK, "SKY_cipher_Address_Null"); + ck_assert(isNull == 0); +} +END_TEST + +START_TEST(TestAddressFromBytes) +{ + cipher__Address addr, addr2; + cipher__SecKey sk; + cipher__PubKey pk; + GoSlice bytes; + GoSlice tempBytes; + GoUint8 buff[1024]; + GoUint32 err = SKY_cipher_GenerateKeyPair(&pk, &sk); + ck_assert(err == SKY_OK); + SKY_cipher_AddressFromPubKey(&pk, &addr); + + tempBytes.data = buff; + tempBytes.len = 0; + tempBytes.cap = sizeof(buff); + + SKY_cipher_Address_Bytes(&addr, &tempBytes); + ck_assert_msg(tempBytes.len > 0, "address bytes written"); + copyGoSlice_toGoSlice(&bytes, (GoSlice_*)&tempBytes, tempBytes.len); + err = SKY_cipher_AddressFromBytes(bytes, &addr2); + ck_assert_msg(err == SKY_OK, "convert bytes to SKY address"); + + ck_assert_msg(isAddressEq(&addr, &addr2), "Not equal Address"); + + int bytes_len = bytes.len; + + bytes.len = bytes.len - 2; + ck_assert_msg(SKY_cipher_AddressFromBytes(bytes, &addr2) == + SKY_ErrAddressInvalidLength, + "no SKY address due to short bytes length"); + + bytes.len = bytes_len; + ((char*)bytes.data)[bytes.len - 1] = '2'; + err = SKY_cipher_AddressFromBytes(bytes, &addr2); + ck_assert_msg(err == SKY_ErrAddressInvalidChecksum, + "no SKY address due to corrupted bytes %X", err); + + addr.Version = 2; + SKY_cipher_Address_Bytes(&addr, &tempBytes); + copyGoSlice_toGoSlice(&bytes, (GoSlice_*)&tempBytes, tempBytes.len); + err = SKY_cipher_AddressFromBytes(bytes, &addr2); + ck_assert_msg(err == SKY_ErrAddressInvalidVersion, "Invalid version"); +} +END_TEST + +// define test suite and cases +Suite* common_check_cipher_address(void) +{ + Suite* s = suite_create("Load cipher.address.common"); + TCase* tc; + + tc = tcase_create("cipher.address.common"); + tcase_add_checked_fixture(tc, setup, teardown); + tcase_add_test(tc, TestAddressFromBytes); + tcase_add_test(tc, TestAddressVerify); + tcase_add_test(tc, TestAddressNull); + suite_add_tcase(s, tc); + tcase_set_timeout(tc, 150); + + return s; +} diff --git a/lib/cgo/tests/check_cipher.bip32.bip32.c b/lib/cgo/tests/check_cipher.bip32.bip32.c new file mode 100755 index 000000000..0c50f713f --- /dev/null +++ b/lib/cgo/tests/check_cipher.bip32.bip32.c @@ -0,0 +1,1180 @@ +#include +#include + +#include "libskycoin.h" +#include "skyerrors.h" +#include "skystring.h" +#include "skytest.h" +#include +#define MAXBUFFER 1024 +#define FirstHardenedChild 0x80000000 + +typedef struct { + GoString path; + GoString privKey; + GoString pubKey; + GoString fingerprint; + GoString identifier; + GoString chainCode; + GoString hexPubKey; + GoString wifPrivKey; + GoUint32_ childNUmber; + GoUint8_ depth; +} testChildKey; + + +typedef struct { + GoString seed; + testChildKey children[MAXBUFFER]; + GoString privkey; + GoString pubKey; + GoString hexPubKey; + GoString wifPrivKey; + GoString fingerprint; + GoString identifier; + GoString chainCode; + GoUint32 childNUmber; + GoUint8 depth; + GoUint32 depthNumber; +} testMasterKey; + + +void assertPrivateKeySerialization(PrivateKey__Handle key, GoString expected) +{ + GoUint8 bufferexpectedBytes[1024]; + GoSlice expectedBytes = {bufferexpectedBytes, 0, 1024}; + GoUint32 err = SKY_base58_Decode(expected, &expectedBytes); + ck_assert_int_eq(SKY_OK, err); + GoUint8 bufferserialized[1024]; + GoSlice serialized = {bufferserialized, 0, 1024}; + err = SKY_bip32_PrivateKey_Serialize(key, &serialized); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoSliceEq(&expectedBytes, &serialized)); + PrivateKey__Handle key2 = 0; + err = SKY_bip32_DeserializePrivateKey(serialized, &key2); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isPrivateKeyEq(key, key2)); + PrivateKey__Handle key3 = 0; + err = SKY_bip32_DeserializeEncodedPrivateKey(expected, &key3); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isPrivateKeyEq(key2, key3)); +} + +void assertPublicKeySerialization(PublicKey__Handle key, GoString expected) +{ + GoUint8 bufferexpectedBytes[1024]; + GoSlice expectedBytes = {bufferexpectedBytes, 0, 1024}; + GoUint32 err = SKY_base58_Decode(expected, &expectedBytes); + ck_assert_int_eq(SKY_OK, err); + GoUint8 bufferserialized[1024]; + GoSlice serialized = {bufferserialized, 0, 1024}; + err = SKY_bip32_PublicKey_Serialize(key, &serialized); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoSliceEq(&expectedBytes, &serialized)); + PublicKey__Handle key2 = 0; + err = SKY_bip32_DeserializePublicKey(serialized, &key2); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isPublicKeyEq(key, key2)); + PublicKey__Handle key3 = 0; + err = SKY_bip32_DeserializeEncodedPublicKey(expected, &key3); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isPublicKeyEq(key2, key3)); +} + +void testVectorKeyPairs(testMasterKey vector) +{ + // Decode master seed into hex + GoUint8 bufferseed[MAXBUFFER]; + GoSlice_ seed = {bufferseed, 0, MAXBUFFER}; + GoUint32 err = SKY_base58_String2Hex(vector.seed, &seed); + ck_assert_int_eq(err, SKY_OK); + + // Generate a master private and public key + PrivateKey__Handle privkey = 0; + GoUint8 buffersliceseed[1024]; + GoSlice sliceseed = {buffersliceseed, 0, 1024}; + copyGoSlice_toGoSlice(&sliceseed, &seed, sizeof(seed)); + err = SKY_bip32_NewMasterKey(sliceseed, &privkey); + ck_assert_int_eq(err, SKY_OK); + PublicKey__Handle pubkey = 0; + err = SKY_bip32_PrivateKey_Publickey(privkey, &pubkey); + ck_assert_int_eq(err, SKY_OK); + + GoUint8 depthPrivKey; + GoUint8 depthPubKey; + err = SKY_bip32_PrivateKey_GetDepth(privkey, &depthPrivKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert_int_eq(0, depthPrivKey); + err = SKY_bip32_PublicKey_GetDepth(pubkey, &depthPubKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert_int_eq(0, depthPubKey); + + GoUint32 childnumberPrivKey; + GoUint32 childnumberPubKey; + err = SKY_bip32_PrivateKey_ChildNumber(privkey, &childnumberPrivKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert_int_eq(0, childnumberPrivKey); + err = SKY_bip32_PublicKey_ChildNumber(pubkey, &childnumberPubKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert_int_eq(0, childnumberPubKey); + + GoUint8 bufferstringPrivKey[1024]; + GoUint8 bufferstringPubKey[1024]; + GoString_ stringPrivKey = {bufferstringPrivKey, 0}; + GoString_ stringPubKey = {bufferstringPubKey, 0}; + err = SKY_bip32_PrivateKey_String(privkey, &stringPrivKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isGoString_toGoStringEq(stringPrivKey, vector.privkey)); + err = SKY_bip32_PublicKey_String(pubkey, &stringPubKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isGoString_toGoStringEq(stringPubKey, vector.pubKey)); + + GoUint8 bufferhexPubKey[1024]; + GoString_ hexPubKey = {bufferhexPubKey, 0}; + GoUint8 bufferpubkey[MAXBUFFER]; + GoSlice_ slicepubkey_tmp = {bufferpubkey, 0, MAXBUFFER}; + err = SKY_bip32_PublicKey_GetKey(pubkey, &slicepubkey_tmp); + ck_assert_int_eq(err, SKY_OK); + GoSlice slicepubkey; + copyGoSlice_toGoSlice(&slicepubkey, &slicepubkey_tmp, slicepubkey_tmp.len); + err = SKY_base58_Hex2String(slicepubkey, &hexPubKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isGoString_toGoStringEq(hexPubKey, vector.hexPubKey)); + + cipher__SecKey tempSec; + GoUint8 bufferprivkey[MAXBUFFER]; + GoSlice_ sliceprivkey_tmp = {bufferprivkey, 0, MAXBUFFER}; + err = SKY_bip32_PrivateKey_GetKey(privkey, &sliceprivkey_tmp); + ck_assert_int_eq(err, SKY_OK); + GoSlice sliceprivkey; + copyGoSlice_toGoSlice(&sliceprivkey, &sliceprivkey_tmp, sliceprivkey_tmp.len); + err = SKY_cipher_NewSecKey(sliceprivkey, &tempSec); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferwif[1024]; + GoString_ wif = {bufferwif, 0}; + SKY_cipher_BitcoinWalletImportFormatFromSeckey(&tempSec, &wif); + ck_assert(isGoString_toGoStringEq(wif, vector.wifPrivKey)); + + GoUint8 bufferprivChainCode[MAXBUFFER]; + GoUint8 bufferpubChainCode[MAXBUFFER]; + GoSlice_ privChainCode_tmp = {bufferprivChainCode, 0, MAXBUFFER}; + GoSlice_ pubChainCode_tmp = {bufferpubChainCode, 0, MAXBUFFER}; + err = SKY_bip32_PrivateKey_GetChainCode(privkey, &privChainCode_tmp); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_GetChainCode(pubkey, &pubChainCode_tmp); + ck_assert_int_eq(SKY_OK, err); + GoString_ priv_ChainCode = {bufferprivChainCode, 0}; + GoString_ pub_ChainCode = {bufferpubChainCode, 0}; + GoSlice privChainCode; + GoSlice pubChainCode; + copyGoSlice_toGoSlice(&privChainCode, &privChainCode_tmp, privChainCode_tmp.len); + err = SKY_base58_Hex2String(privChainCode, &priv_ChainCode); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(priv_ChainCode, vector.chainCode)); + copyGoSlice_toGoSlice(&pubChainCode, &pubChainCode_tmp, pubChainCode_tmp.len); + err = SKY_base58_Hex2String(pubChainCode, &pub_ChainCode); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(pub_ChainCode, vector.chainCode)); + + GoUint8 bufferprivFringerprint[MAXBUFFER]; + GoUint8 bufferpubFringerprint[MAXBUFFER]; + GoSlice_ privFringerprint_tmp = {bufferprivFringerprint, 0, MAXBUFFER}; + GoSlice_ pubFringerprint_tmp = {bufferpubFringerprint, 0, MAXBUFFER}; + GoUint8 bufferpriv_Fringerprint[MAXBUFFER]; + GoString priv_Fringerprint = {bufferpriv_Fringerprint, 0}; + GoUint8 bufferpub_Fringerprint[MAXBUFFER]; + GoString pub_Fringerprint = {bufferpub_Fringerprint, 0}; + err = SKY_bip32_PrivateKey_Fingerprint(privkey, &privFringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_Fingerprint(pubkey, &pubFringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + GoSlice privFringerprint; + copyGoSlice_toGoSlice(&privFringerprint, &privFringerprint_tmp, privFringerprint_tmp.len); + GoSlice pubFringerprint; + + GoString_ priv_Fringerprint_tmp; + GoString_ pub_Fringerprint_tmp; + err = SKY_base58_Hex2String(privFringerprint, &priv_Fringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + copyGoSlice_toGoSlice(&pubFringerprint, &pubFringerprint_tmp, pubFringerprint_tmp.len); + err = SKY_base58_Hex2String(pubFringerprint, &pub_Fringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(priv_Fringerprint_tmp, vector.fingerprint)); + ck_assert(isGoString_toGoStringEq(pub_Fringerprint_tmp, vector.fingerprint)); + + GoSlice_ privIdentifier_tmp; + GoSlice_ pubIdentifier_tmp; + GoString_ priv_Identifier; + GoString_ pub_Identifier; + err = SKY_bip32_PrivateKey_Identifier(privkey, &privIdentifier_tmp); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_Identifier(pubkey, &pubIdentifier_tmp); + ck_assert_int_eq(SKY_OK, err); + GoSlice privIdentifier; + GoSlice pubIdentifier; + copyGoSlice_toGoSlice(&privIdentifier, &privIdentifier_tmp, privIdentifier_tmp.len); + copyGoSlice_toGoSlice(&pubIdentifier, &pubIdentifier_tmp, pubIdentifier_tmp.len); + err = SKY_base58_Hex2String(privIdentifier, &priv_Identifier); + ck_assert_int_eq(SKY_OK, err); + err = SKY_base58_Hex2String(pubIdentifier, &pub_Identifier); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(priv_Identifier, vector.identifier)); + ck_assert(isGoString_toGoStringEq(pub_Identifier, vector.identifier)); + + GoUint8 privDepth; + GoUint8 pubDepth; + err = SKY_bip32_PrivateKey_GetDepth(privkey, &privDepth); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_GetDepth(pubkey, &pubDepth); + ck_assert_int_eq(SKY_OK, err); + ck_assert_int_eq(vector.depth, privDepth); + ck_assert_int_eq(vector.depth, pubDepth); + + GoUint32 privchildNumber; + GoUint32 pubchildNumber; + err = SKY_bip32_PrivateKey_ChildNumber(privkey, &privchildNumber); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_ChildNumber(pubkey, &pubchildNumber); + ck_assert_int_eq(SKY_OK, err); + ck_assert_int_eq(vector.childNUmber, privchildNumber); + ck_assert_int_eq(vector.childNUmber, pubchildNumber); + + // Serialize and deserialize both keys and ensure they're the same + assertPrivateKeySerialization(privkey, vector.privkey); + assertPublicKeySerialization(pubkey, vector.pubKey); + + GoSlice_ b58pk_tmp; + err = SKY_base58_Decode(vector.privkey, &b58pk_tmp); + ck_assert_int_eq(SKY_OK, err); + PrivateKey__Handle privKey2 = 0; + GoSlice b58pk; + copyGoSlice_toGoSlice(&b58pk, &b58pk_tmp, b58pk_tmp.len); + err = SKY_bip32_DeserializePrivateKey(b58pk, &privKey2); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isPrivateKeyEq(privkey, privKey2)); + + // Test that DeserializeEncodedPrivateKey + // is equivalent to DeserializePrivateKey(base58.Decode(key)) + PrivateKey__Handle privKey3 = 0; + err = SKY_bip32_DeserializeEncodedPrivateKey(vector.privkey, &privKey3); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isPrivateKeyEq(privKey2, privKey3)); + + // Iterate over the entire child chain and test the given keys + for (size_t i = 0; i < vector.depthNumber; i++) { + printf("Iter %d\n", i); + testChildKey tck = vector.children[i]; + privkey = 0; + err = SKY_bip32_NewPrivateKeyFromPath(sliceseed, tck.path, &privkey); + ck_assert_int_eq(SKY_OK, err); + + // Get this private key's public key + pubkey = 0; + err = SKY_bip32_PrivateKey_Publickey(privkey, &pubkey); + ck_assert_int_eq(SKY_OK, err); + + // Test DeserializePrivateKey + GoUint8 bufferppk[MAXBUFFER]; + GoSlice_ ppk_tmp = {bufferppk, 0, MAXBUFFER}; + err = SKY_base58_Decode(tck.privKey, &ppk_tmp); + ck_assert_int_eq(SKY_OK, err); + PrivateKey__Handle xx = 0; + GoSlice ppk; + copyGoSlice_toGoSlice(&ppk, &ppk_tmp, ppk_tmp.len); + err = SKY_bip32_DeserializePrivateKey(ppk, &xx); + ck_assert_int_eq(SKY_OK, err); + + ck_assert(isPrivateKeyEq(xx, privkey)); + + err = SKY_bip32_PrivateKey_String(privkey, &stringPrivKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isGoString_toGoStringEq(stringPrivKey, tck.privKey)); + err = SKY_bip32_PublicKey_String(pubkey, &stringPubKey); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isGoString_toGoStringEq(stringPubKey, tck.pubKey)); + + err = SKY_bip32_PrivateKey_GetChainCode(privkey, &privChainCode); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_GetChainCode(pubkey, &pubChainCode); + ck_assert_int_eq(SKY_OK, err); + err = SKY_base58_Hex2String(privChainCode, &priv_ChainCode); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(priv_ChainCode, tck.chainCode)); + err = SKY_base58_Hex2String(pubChainCode, &pub_ChainCode); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(pub_ChainCode, tck.chainCode)); + + GoSlice_ privFringerprint_tmp; + err = SKY_bip32_PrivateKey_Fingerprint(privkey, &privFringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + GoSlice_ pubFringerprint_tmp; + err = SKY_bip32_PublicKey_Fingerprint(pubkey, &pubFringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + copyGoSlice_toGoSlice(&privFringerprint, &privFringerprint_tmp, privFringerprint_tmp.len); + err = SKY_base58_Hex2String(privFringerprint, &priv_Fringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + copyGoSlice_toGoSlice(&pubFringerprint, &pubFringerprint_tmp, pubFringerprint_tmp.len); + err = SKY_base58_Hex2String(pubFringerprint, &pub_Fringerprint_tmp); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(pub_Fringerprint_tmp, tck.fingerprint)); + ck_assert(isGoString_toGoStringEq(pub_Fringerprint_tmp, tck.fingerprint)); + + err = SKY_bip32_PrivateKey_Identifier(privkey, &privIdentifier); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_Identifier(pubkey, &pubIdentifier); + ck_assert_int_eq(SKY_OK, err); + err = SKY_base58_Hex2String(privIdentifier, &priv_Identifier); + ck_assert_int_eq(SKY_OK, err); + err = SKY_base58_Hex2String(pubIdentifier, &pub_Identifier); + ck_assert_int_eq(SKY_OK, err); + ck_assert(isGoString_toGoStringEq(priv_Identifier, tck.identifier)); + ck_assert(isGoString_toGoStringEq(pub_Identifier, tck.identifier)); + + err = SKY_bip32_PrivateKey_GetDepth(privkey, &privDepth); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_GetDepth(pubkey, &pubDepth); + ck_assert_int_eq(SKY_OK, err); + ck_assert_int_eq(tck.depth, privDepth); + ck_assert_int_eq(tck.depth, pubDepth); + + err = SKY_bip32_PrivateKey_ChildNumber(privkey, &privchildNumber); + ck_assert_int_eq(SKY_OK, err); + err = SKY_bip32_PublicKey_ChildNumber(pubkey, &pubchildNumber); + ck_assert_int_eq(SKY_OK, err); + ck_assert_int_eq(tck.childNUmber, privchildNumber); + ck_assert_int_eq(tck.childNUmber, pubchildNumber); + + // Serialize and deserialize both keys and ensure they're the same + assertPrivateKeySerialization(privkey, tck.privKey); + assertPublicKeySerialization(pubkey, tck.pubKey); + } +} + +START_TEST(TestBip32TestVectors) +{ + printf("Load TestBip32TestVectors\n"); + testMasterKey vector1; + vector1.seed.p = "000102030405060708090a0b0c0d0e0f"; + vector1.seed.n = 32; + vector1.privkey.p = "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"; + vector1.privkey.n = 111; + vector1.pubKey.p = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8"; + vector1.pubKey.n = 111; + vector1.hexPubKey.p = "0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2"; + vector1.hexPubKey.n = 66; + vector1.wifPrivKey.p = "L52XzL2cMkHxqxBXRyEpnPQZGUs3uKiL3R11XbAdHigRzDozKZeW"; + vector1.wifPrivKey.n = 52; + vector1.fingerprint.p = "3442193e"; + vector1.fingerprint.n = 8; + vector1.identifier.p = "3442193e1bb70916e914552172cd4e2dbc9df811"; + vector1.identifier.n = 40; + vector1.chainCode.p = "873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508"; + vector1.chainCode.n = 64; + vector1.childNUmber = 0; + vector1.depth = 0; + vector1.depthNumber = 5; + // 0 + vector1.children[0].path.p = "m/0'"; + vector1.children[0].path.n = 4; + vector1.children[0].privKey.p = "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7"; + vector1.children[0].privKey.n = 111; + vector1.children[0].pubKey.p = "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw"; + vector1.children[0].pubKey.n = 111; + vector1.children[0].fingerprint.p = "5c1bd648"; + vector1.children[0].fingerprint.n = 8; + vector1.children[0].identifier.p = "5c1bd648ed23aa5fd50ba52b2457c11e9e80a6a7"; + vector1.children[0].identifier.n = 40; + vector1.children[0].chainCode.p = "47fdacbd0f1097043b78c63c20c34ef4ed9a111d980047ad16282c7ae6236141"; + vector1.children[0].chainCode.n = 64; + vector1.children[0].hexPubKey.p = "035a784662a4a20a65bf6aab9ae98a6c068a81c52e4b032c0fb5400c706cfccc56"; + vector1.children[0].hexPubKey.n = 66; + vector1.children[0].wifPrivKey.p = "L5BmPijJjrKbiUfG4zbiFKNqkvuJ8usooJmzuD7Z8dkRoTThYnAT"; + vector1.children[0].wifPrivKey.n = 52; + vector1.children[0].childNUmber = 2147483648; + vector1.children[0].depth = 1; + // 1 + vector1.children[1].path.p = "m/0'/1"; + vector1.children[1].path.n = 6; + vector1.children[1].privKey.p = "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs"; + vector1.children[1].privKey.n = 111; + vector1.children[1].pubKey.p = "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ"; + vector1.children[1].pubKey.n = 111; + vector1.children[1].fingerprint.p = "bef5a2f9"; + vector1.children[1].fingerprint.n = 8; + vector1.children[1].identifier.p = "bef5a2f9a56a94aab12459f72ad9cf8cf19c7bbe"; + vector1.children[1].identifier.n = 40; + vector1.children[1].chainCode.p = "2a7857631386ba23dacac34180dd1983734e444fdbf774041578e9b6adb37c19"; + vector1.children[1].chainCode.n = 64; + vector1.children[1].hexPubKey.p = "03501e454bf00751f24b1b489aa925215d66af2234e3891c3b21a52bedb3cd711c"; + vector1.children[1].hexPubKey.n = 66; + vector1.children[1].wifPrivKey.p = "KyFAjQ5rgrKvhXvNMtFB5PCSKUYD1yyPEe3xr3T34TZSUHycXtMM"; + vector1.children[1].wifPrivKey.n = 52; + vector1.children[1].childNUmber = 1; + vector1.children[1].depth = 2; + // 2 + vector1.children[2].path.p = "m/0'/1/2'"; + vector1.children[2].path.n = 9; + vector1.children[2].privKey.p = "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM"; + vector1.children[2].privKey.n = 111; + vector1.children[2].pubKey.p = "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5"; + vector1.children[2].pubKey.n = 111; + vector1.children[2].fingerprint.p = "ee7ab90c"; + vector1.children[2].fingerprint.n = 8; + vector1.children[2].identifier.p = "ee7ab90cde56a8c0e2bb086ac49748b8db9dce72"; + vector1.children[2].identifier.n = 40; + vector1.children[2].chainCode.p = "04466b9cc8e161e966409ca52986c584f07e9dc81f735db683c3ff6ec7b1503f"; + vector1.children[2].chainCode.n = 64; + vector1.children[2].hexPubKey.p = "0357bfe1e341d01c69fe5654309956cbea516822fba8a601743a012a7896ee8dc2"; + vector1.children[2].hexPubKey.n = 66; + vector1.children[2].wifPrivKey.p = "L43t3od1Gh7Lj55Bzjj1xDAgJDcL7YFo2nEcNaMGiyRZS1CidBVU"; + vector1.children[2].wifPrivKey.n = 52; + vector1.children[2].childNUmber = 2 + FirstHardenedChild; + vector1.children[2].depth = 3; + // 3 + vector1.children[3].path.p = "m/0'/1/2'/2"; + vector1.children[3].path.n = 11; + vector1.children[3].privKey.p = "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334"; + vector1.children[3].privKey.n = 111; + vector1.children[3].pubKey.p = "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV"; + vector1.children[3].pubKey.n = 111; + vector1.children[3].fingerprint.p = "d880d7d8"; + vector1.children[3].fingerprint.n = 8; + vector1.children[3].identifier.p = "d880d7d893848509a62d8fb74e32148dac68412f"; + vector1.children[3].identifier.n = 40; + vector1.children[3].chainCode.p = "cfb71883f01676f587d023cc53a35bc7f88f724b1f8c2892ac1275ac822a3edd"; + vector1.children[3].chainCode.n = 64; + vector1.children[3].hexPubKey.p = "02e8445082a72f29b75ca48748a914df60622a609cacfce8ed0e35804560741d29"; + vector1.children[3].hexPubKey.n = 66; + vector1.children[3].wifPrivKey.p = "KwjQsVuMjbCP2Zmr3VaFaStav7NvevwjvvkqrWd5Qmh1XVnCteBR"; + vector1.children[3].wifPrivKey.n = 52; + vector1.children[3].childNUmber = 2; + vector1.children[3].depth = 4; + // 4 + vector1.children[4].path.p = "m/0'/1/2'/2/1000000000"; + vector1.children[4].path.n = 22; + vector1.children[4].privKey.p = "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76"; + vector1.children[4].privKey.n = 111; + vector1.children[4].pubKey.p = "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy"; + vector1.children[4].pubKey.n = 111; + vector1.children[4].fingerprint.p = "d69aa102"; + vector1.children[4].fingerprint.n = 8; + vector1.children[4].identifier.p = "d69aa102255fed74378278c7812701ea641fdf32"; + vector1.children[4].identifier.n = 40; + vector1.children[4].chainCode.p = "c783e67b921d2beb8f6b389cc646d7263b4145701dadd2161548a8b078e65e9e"; + vector1.children[4].chainCode.n = 64; + vector1.children[4].hexPubKey.p = "022a471424da5e657499d1ff51cb43c47481a03b1e77f951fe64cec9f5a48f7011"; + vector1.children[4].hexPubKey.n = 66; + vector1.children[4].wifPrivKey.p = "Kybw8izYevo5xMh1TK7aUr7jHFCxXS1zv8p3oqFz3o2zFbhRXHYs"; + vector1.children[4].wifPrivKey.n = 52; + vector1.children[4].childNUmber = 1000000000; + vector1.children[4].depth = 5; + // vector 2 + testMasterKey vector2; + vector2.seed.p = "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542"; + vector2.seed.n = 128; + vector2.privkey.p = "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U"; + vector2.privkey.n = 111; + vector2.pubKey.p = "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB"; + vector2.pubKey.n = 111; + vector2.hexPubKey.p = "03cbcaa9c98c877a26977d00825c956a238e8dddfbd322cce4f74b0b5bd6ace4a7"; + vector2.hexPubKey.n = 66; + vector2.wifPrivKey.p = "KyjXhyHF9wTphBkfpxjL8hkDXDUSbE3tKANT94kXSyh6vn6nKaoy"; + vector2.wifPrivKey.n = 52; + vector2.fingerprint.p = "bd16bee5"; + vector2.fingerprint.n = 8; + vector2.identifier.p = "bd16bee53961a47d6ad888e29545434a89bdfe95"; + vector2.identifier.n = 40; + vector2.chainCode.p = "60499f801b896d83179a4374aeb7822aaeaceaa0db1f85ee3e904c4defbd9689"; + vector2.chainCode.n = 64; + vector2.childNUmber = 0; + vector2.depth = 0; + vector2.depthNumber = 5; + // 0 + vector2.children[0].path.p = "m/0"; + vector2.children[0].path.n = 3; + vector2.children[0].privKey.p = "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt"; + vector2.children[0].privKey.n = 111; + vector2.children[0].pubKey.p = "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH"; + vector2.children[0].pubKey.n = 111; + vector2.children[0].fingerprint.p = "5a61ff8e"; + vector2.children[0].fingerprint.n = 8; + vector2.children[0].identifier.p = "5a61ff8eb7aaca3010db97ebda76121610b78096"; + vector2.children[0].identifier.n = 40; + vector2.children[0].chainCode.p = "f0909affaa7ee7abe5dd4e100598d4dc53cd709d5a5c2cac40e7412f232f7c9c"; + vector2.children[0].chainCode.n = 64; + vector2.children[0].hexPubKey.p = "02fc9e5af0ac8d9b3cecfe2a888e2117ba3d089d8585886c9c826b6b22a98d12ea"; + vector2.children[0].hexPubKey.n = 66; + vector2.children[0].wifPrivKey.p = "L2ysLrR6KMSAtx7uPqmYpoTeiRzydXBattRXjXz5GDFPrdfPzKbj"; + vector2.children[0].wifPrivKey.n = 52; + vector2.children[0].childNUmber = 0; + vector2.children[0].depth = 1; + // 1 + vector2.children[1].path.p = "m/0/2147483647'"; + vector2.children[1].path.n = 15; + vector2.children[1].privKey.p = "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9"; + vector2.children[1].privKey.n = 111; + vector2.children[1].pubKey.p = "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a"; + vector2.children[1].pubKey.n = 111; + vector2.children[1].fingerprint.p = "d8ab4937"; + vector2.children[1].fingerprint.n = 8; + vector2.children[1].identifier.p = "d8ab493736da02f11ed682f88339e720fb0379d1"; + vector2.children[1].identifier.n = 40; + vector2.children[1].chainCode.p = "be17a268474a6bb9c61e1d720cf6215e2a88c5406c4aee7b38547f585c9a37d9"; + vector2.children[1].chainCode.n = 64; + vector2.children[1].hexPubKey.p = "03c01e7425647bdefa82b12d9bad5e3e6865bee0502694b94ca58b666abc0a5c3b"; + vector2.children[1].hexPubKey.n = 66; + vector2.children[1].wifPrivKey.p = "L1m5VpbXmMp57P3knskwhoMTLdhAAaXiHvnGLMribbfwzVRpz2Sr"; + vector2.children[1].wifPrivKey.n = 52; + vector2.children[1].childNUmber = 2147483647 + FirstHardenedChild; + vector2.children[1].depth = 2; + // 2 + vector2.children[2].path.p = "m/0/2147483647'/1"; + vector2.children[2].path.n = 17; + vector2.children[2].privKey.p = "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef"; + vector2.children[2].privKey.n = 111; + vector2.children[2].pubKey.p = "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon"; + vector2.children[2].pubKey.n = 111; + vector2.children[2].fingerprint.p = "78412e3a"; + vector2.children[2].fingerprint.n = 8; + vector2.children[2].identifier.p = "78412e3a2296a40de124307b6485bd19833e2e34"; + vector2.children[2].identifier.n = 40; + vector2.children[2].chainCode.p = "f366f48f1ea9f2d1d3fe958c95ca84ea18e4c4ddb9366c336c927eb246fb38cb"; + vector2.children[2].chainCode.n = 64; + vector2.children[2].hexPubKey.p = "03a7d1d856deb74c508e05031f9895dab54626251b3806e16b4bd12e781a7df5b9"; + vector2.children[2].hexPubKey.n = 66; + vector2.children[2].wifPrivKey.p = "KzyzXnznxSv249b4KuNkBwowaN3akiNeEHy5FWoPCJpStZbEKXN2"; + vector2.children[2].wifPrivKey.n = 52; + vector2.children[2].childNUmber = 1; + vector2.children[2].depth = 3; + // 3 + vector2.children[3].path.p = "m/0/2147483647'/1/2147483646'"; + vector2.children[3].path.n = 29; + vector2.children[3].privKey.p = "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc"; + vector2.children[3].privKey.n = 111; + vector2.children[3].pubKey.p = "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL"; + vector2.children[3].pubKey.n = 111; + vector2.children[3].fingerprint.p = "31a507b8"; + vector2.children[3].fingerprint.n = 8; + vector2.children[3].identifier.p = "31a507b815593dfc51ffc7245ae7e5aee304246e"; + vector2.children[3].identifier.n = 40; + vector2.children[3].chainCode.p = "637807030d55d01f9a0cb3a7839515d796bd07706386a6eddf06cc29a65a0e29"; + vector2.children[3].chainCode.n = 64; + vector2.children[3].hexPubKey.p = "02d2b36900396c9282fa14628566582f206a5dd0bcc8d5e892611806cafb0301f0"; + vector2.children[3].hexPubKey.n = 66; + vector2.children[3].wifPrivKey.p = "L5KhaMvPYRW1ZoFmRjUtxxPypQ94m6BcDrPhqArhggdaTbbAFJEF"; + vector2.children[3].wifPrivKey.n = 52; + vector2.children[3].childNUmber = 2147483646 + FirstHardenedChild; + vector2.children[3].depth = 4; + // 4 + vector2.children[4].path.p = "m/0/2147483647'/1/2147483646'/2"; + vector2.children[4].path.n = 31; + vector2.children[4].privKey.p = "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"; + vector2.children[4].privKey.n = 111; + vector2.children[4].pubKey.p = "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt"; + vector2.children[4].pubKey.n = 111; + vector2.children[4].fingerprint.p = "26132fdb"; + vector2.children[4].fingerprint.n = 8; + vector2.children[4].identifier.p = "26132fdbe7bf89cbc64cf8dafa3f9f88b8666220"; + vector2.children[4].identifier.n = 40; + vector2.children[4].chainCode.p = "9452b549be8cea3ecb7a84bec10dcfd94afe4d129ebfd3b3cb58eedf394ed271"; + vector2.children[4].chainCode.n = 64; + vector2.children[4].hexPubKey.p = "024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c"; + vector2.children[4].hexPubKey.n = 66; + vector2.children[4].wifPrivKey.p = "L3WAYNAZPxx1fr7KCz7GN9nD5qMBnNiqEJNJMU1z9MMaannAt4aK"; + vector2.children[4].wifPrivKey.n = 52; + vector2.children[4].childNUmber = 2; + vector2.children[4].depth = 5; + + // Vector 3 + testMasterKey vector3; + vector3.seed.p = "4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be"; + vector3.seed.n = 128; + vector3.privkey.p = "xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6"; + vector3.privkey.n = 111; + vector3.pubKey.p = "xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13"; + vector3.pubKey.n = 111; + vector3.hexPubKey.p = "03683af1ba5743bdfc798cf814efeeab2735ec52d95eced528e692b8e34c4e5669"; + vector3.hexPubKey.n = 66; + vector3.wifPrivKey.p = "KwFPqAq9SKx1sPg15Qk56mqkHwrfGPuywtLUxoWPkiTSBoxCs8am"; + vector3.wifPrivKey.n = 52; + vector3.fingerprint.p = "41d63b50"; + vector3.fingerprint.n = 8; + vector3.identifier.p = "41d63b50d8dd5e730cdf4c79a56fc929a757c548"; + vector3.identifier.n = 40; + vector3.chainCode.p = "01d28a3e53cffa419ec122c968b3259e16b65076495494d97cae10bbfec3c36f"; + vector3.chainCode.n = 64; + vector3.childNUmber = 0; + vector3.depth = 0; + vector3.depthNumber = 1; + // 0 + vector3.children[0].path.p = "m/0'"; + vector3.children[0].path.n = 4; + vector3.children[0].privKey.p = "xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L"; + vector3.children[0].privKey.n = 111; + vector3.children[0].pubKey.p = "xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y"; + vector3.children[0].pubKey.n = 111; + vector3.children[0].fingerprint.p = "c61368bb"; + vector3.children[0].fingerprint.n = 8; + vector3.children[0].identifier.p = "c61368bb50e066acd95bd04a0b23d3837fb75698"; + vector3.children[0].identifier.n = 40; + vector3.children[0].chainCode.p = "e5fea12a97b927fc9dc3d2cb0d1ea1cf50aa5a1fdc1f933e8906bb38df3377bd"; + vector3.children[0].chainCode.n = 64; + vector3.children[0].hexPubKey.p = "027c3591221e28939e45f8ea297d62c3640ebb09d7058b01d09c963d984a40ad49"; + vector3.children[0].hexPubKey.n = 66; + vector3.children[0].wifPrivKey.p = "L3z3MSqZtDQ1FPHKi7oWf1nc9rMEGFtZUDCoFa7n4F695g5qZiSu"; + vector3.children[0].wifPrivKey.n = 52; + vector3.children[0].childNUmber = FirstHardenedChild; + vector3.children[0].depth = 1; + + testMasterKey vector4; + vector4.seed.p = "d13de7bd1e54422d1a3b3b699a27fb460de2849e7e66a005c647e8e4a54075cb"; + vector4.seed.n = 64; + vector4.privkey.p = "xprv9s21ZrQH143K3zWpEJm5QtHFh93eNJrNbNqzqLN5XoE9MvC7gs5TmBFaL2PpaXpDc8FBYVe5EChc73ApjSQ5fWsXS7auHy1MmG6hdpywE1q"; + vector4.privkey.n = 111; + vector4.pubKey.p = "xpub661MyMwAqRbcGUbHLLJ5n2DzFAt8mmaDxbmbdimh68m8EiXGEQPiJya4BJat5yMzy4e68VSUoLGCu5uvzf8dUoGvwuJsLE6F1cibmWsxFNn"; + vector4.pubKey.n = 111; + vector4.hexPubKey.p = "0298ccc720d5dea817c7077605263bae52bca083cf8888fee77ff4c1b4797ee180"; + vector4.hexPubKey.n = 66; + vector4.wifPrivKey.p = "KwDiCU5bs8xQwsRgxjhkcJcVuR7NE4Mei8X9uSAVviVTE7JmMoS6"; + vector4.wifPrivKey.n = 52; + vector4.fingerprint.p = "1a87677b"; + vector4.fingerprint.n = 8; + vector4.identifier.p = "1a87677be6f73cc9655e8b4c5d2fd0aeeb1b23c7"; + vector4.identifier.n = 40; + vector4.chainCode.p = "c23ab32b36ddff49fae350a1bed8ec6b4d9fc252238dd789b7273ba4416054eb"; + vector4.chainCode.n = 64; + vector4.childNUmber = 0; + vector4.depth = 0; + vector4.depthNumber = 0; + // 0 + vector4.children[0].path.p = "m/44'/0'/0'/0/0'"; + vector4.children[0].path.n = 16; + vector4.children[0].privKey.p = "xprvA3cqPFaMpr7n1wRh6BPtYfwdYRoKCaPzgDdQnUmgMrz1WxWNEW3EmbBr9ieh9BJAsRGKFPLvotb4p4Aq79jddUVKPVJt7exVzLHcv777JVf"; + vector4.children[0].privKey.n = 111; + vector4.children[0].pubKey.p = "xpub6GcBnm7FfDg5ERWACCvtuotN6Tdoc37r3SZ1asBHvCWzPkqWn3MVKPWKzy6GsfmdMUGanR3D12dH1cp5tJauuubwc4FAJDn67SH2uUjwAT1"; + vector4.children[0].pubKey.n = 111; + vector4.children[0].fingerprint.p = "e371d69b"; + vector4.children[0].fingerprint.n = 8; + vector4.children[0].identifier.p = "e371d69b5dae6eacee832a130ee9f55545275a09"; + vector4.children[0].identifier.n = 40; + vector4.children[0].chainCode.p = "ca27553aa89617e982e621637d6478f564b32738f8bbe2e48d0a58a8e0f6da40"; + vector4.children[0].chainCode.n = 64; + vector4.children[0].hexPubKey.p = "027c3591221e28939e45f8ea297d62c3640ebb09d7058b01d09c963d984a40ad49"; + vector4.children[0].hexPubKey.n = 66; + vector4.children[0].wifPrivKey.p = "L3z3MSqZtDQ1FPHKi7oWf1nc9rMEGFtZUDCoFa7n4F695g5qZiSu"; + vector4.children[0].wifPrivKey.n = 52; + vector4.children[0].childNUmber = FirstHardenedChild; + vector4.children[0].depth = 5; + + printf("Vector 1\n"); + testVectorKeyPairs(vector1); + printf("Vector 2\n"); + testVectorKeyPairs(vector2); + printf("Vector 3\n"); + testVectorKeyPairs(vector3); + printf("Vector 4\n"); + testVectorKeyPairs(vector4); +} +END_TEST + +START_TEST(TestParentPublicChildDerivation) +{ + printf("Load TestParentPublicChildDerivation\n"); + GoUint8 buffer_extendedMasterPublicBytes_tmp[1024]; + GoSlice_ extendedMasterPublicBytes_tmp = {buffer_extendedMasterPublicBytes_tmp, 0, 1024}; + GoString tmp_str = {"xpub6DxSCdWu6jKqr4isjo7bsPeDD6s3J4YVQV1JSHZg12Eagdqnf7XX4fxqyW2sLhUoFWutL7tAELU2LiGZrEXtjVbvYptvTX5Eoa4Mamdjm9u", 111}; + GoUint32 err = SKY_base58_Decode(tmp_str, &extendedMasterPublicBytes_tmp); + ck_assert_int_eq(err, SKY_OK); + + PublicKey__Handle extendedMasterPublic = 0; + GoUint8 buffer_extendedMasterPublicBytes[1024]; + GoSlice extendedMasterPublicBytes = {buffer_extendedMasterPublicBytes, 0, 1024}; + copyGoSlice_toGoSlice(&extendedMasterPublicBytes, &extendedMasterPublicBytes_tmp, extendedMasterPublicBytes_tmp.len); + err = SKY_bip32_DeserializePublicKey(extendedMasterPublicBytes, &extendedMasterPublic); + ck_assert_int_eq(err, SKY_OK); + + GoUint8 buffer_extendedMasterPrivateBytes_tmp[1024]; + GoSlice_ extendedMasterPrivateBytes_tmp = {buffer_extendedMasterPrivateBytes_tmp, 0, 1024}; + tmp_str.p = "xprv9zy5o7z1GMmYdaeQdmabWFhUf52Ytbpe3G5hduA4SghboqWe7aDGWseN8BJy1GU72wPjkCbBE1hvbXYqpCecAYdaivxjNnBoSNxwYD4wHpW"; + tmp_str.n = 111; + err = SKY_base58_Decode(tmp_str, &extendedMasterPrivateBytes_tmp); + ck_assert_int_eq(err, SKY_OK); + + PrivateKey__Handle extendedMasterPrivate = 0; + GoUint8 buffer_extendedMasterPrivateBytes[1024]; + GoSlice extendedMasterPrivateBytes = {buffer_extendedMasterPrivateBytes, 0, 1024}; + copyGoSlice_toGoSlice(&extendedMasterPrivateBytes, &extendedMasterPrivateBytes_tmp, extendedMasterPrivateBytes_tmp.len); + err = SKY_bip32_DeserializePrivateKey(extendedMasterPrivateBytes, &extendedMasterPrivate); + ck_assert_int_eq(err, SKY_OK); + + testChildKey expectedChildren[MAXBUFFER]; + // 0 + expectedChildren[0].path.p = "m/0"; + expectedChildren[0].path.n = 3; + expectedChildren[0].hexPubKey.p = "0243187e1a2ba9ba824f5f81090650c8f4faa82b7baf93060d10b81f4b705afd46"; + expectedChildren[0].hexPubKey.n = 66; + expectedChildren[0].wifPrivKey.p = "KyNPkzzaQ9xa7d2iFacTBgjP4rM3SydTzUZW7uwDh6raePWRJkeM"; + expectedChildren[0].wifPrivKey.n = 52; + // 1 + expectedChildren[1].path.p = "m/1"; + expectedChildren[1].path.n = 3; + expectedChildren[1].hexPubKey.p = "023790d11eb715c4320d8e31fba3a09b700051dc2cdbcce03f44b11c274d1e220b"; + expectedChildren[1].hexPubKey.n = 66; + expectedChildren[1].wifPrivKey.p = "KwVyk5XXaamsPPiGLHciv6AjhUV88CM7xTto7sRMCEy12GfwZzZQ"; + expectedChildren[1].wifPrivKey.n = 52; + // 2 + expectedChildren[2].path.p = "m/2"; + expectedChildren[2].path.n = 3; + expectedChildren[2].hexPubKey.p = "0302c5749c3c75cea234878ae3f4d8f65b75d584bcd7ed0943b016d6f6b59a2bad"; + expectedChildren[2].hexPubKey.n = 66; + expectedChildren[2].wifPrivKey.p = "L1o7CpgTjkcBYmbeuNigVpypgJ9GKq87WNqz8QDjWMqdKVKFf826"; + expectedChildren[2].wifPrivKey.n = 52; + // 3 + expectedChildren[3].path.p = "m/3"; + expectedChildren[3].path.n = 3; + expectedChildren[3].hexPubKey.p = "03f0440c94e5b14ea5b15875934597afff541bec287c6e65dc1102cafc07f69699"; + expectedChildren[3].hexPubKey.n = 66; + expectedChildren[3].wifPrivKey.p = "KzmYqf8WSUNzf2LhAWJjxv7pYX34XhFeLLxSoaSD8y9weJ4j6Z7q"; + expectedChildren[3].wifPrivKey.n = 52; + // 4 + expectedChildren[4].path.p = "m/4"; + expectedChildren[4].path.n = 3; + expectedChildren[4].hexPubKey.p = "026419d0d8996707605508ac44c5871edc7fe206a79ef615b74f2eea09c5852e2b"; + expectedChildren[4].hexPubKey.n = 66; + expectedChildren[4].wifPrivKey.p = "KzezMKd7Yc4jwJd6ASji2DwXX8jB8XwNTggLoAJU78zPAfXhzRLD"; + expectedChildren[4].wifPrivKey.n = 52; + // 5 + expectedChildren[5].path.p = "m/5"; + expectedChildren[5].path.n = 3; + expectedChildren[5].hexPubKey.p = "02f63c6f195eea98bdb163c4a094260dea71d264b21234bed4df3899236e6c2298"; + expectedChildren[5].hexPubKey.n = 66; + expectedChildren[5].wifPrivKey.p = "Kwxik5cHiQCZYy5g9gdfQmr7c3ivLDhFjpSF7McHKHeox6iu6MjL"; + expectedChildren[5].wifPrivKey.n = 52; + // 6 + expectedChildren[6].path.p = "m/6"; + expectedChildren[6].path.n = 3; + expectedChildren[6].hexPubKey.p = "02d74709cd522081064858f393d009ead5a0ecd43ede3a1f57befcc942025cb5f9"; + expectedChildren[6].hexPubKey.n = 66; + expectedChildren[6].wifPrivKey.p = "KwGhZYHovZoczyfupFRgZcr2xz1nHTSKx79uZuWhuzDSU7L7LrxE"; + expectedChildren[6].wifPrivKey.n = 52; + // 7 + expectedChildren[7].path.p = "m/7"; + expectedChildren[7].path.n = 3; + expectedChildren[7].hexPubKey.p = "03e54bb92630c943d38bbd8a4a2e65fca7605e672d30a0e545a7198cbb60729ceb"; + expectedChildren[7].hexPubKey.n = 66; + expectedChildren[7].wifPrivKey.p = "L4iGJ3JCfnMU1ia2bMQeF88hs6tkkS9QrmLbWPsj1ULHrUJid4KT"; + expectedChildren[7].wifPrivKey.n = 52; + // 8 + expectedChildren[8].path.p = "m/8"; + expectedChildren[8].path.n = 3; + expectedChildren[8].hexPubKey.p = "027e9d5acd14d39c4938697fba388cd2e8f31fc1c5dc02fafb93a10a280de85199"; + expectedChildren[8].hexPubKey.n = 66; + expectedChildren[8].wifPrivKey.p = "L3xfynMTDMR8vs6G5VxxjoKLBQyihvtcBHF4KHY5wvFMwevLjZKU"; + expectedChildren[8].wifPrivKey.n = 52; + // 9 + expectedChildren[9].path.p = "m/9"; + expectedChildren[9].path.n = 3; + expectedChildren[9].hexPubKey.p = "02a167a9f0d57468fb6abf2f3f7967e2cadf574314753a06a9ef29bc76c54638d2"; + expectedChildren[9].hexPubKey.n = 66; + expectedChildren[9].wifPrivKey.p = "KxiUV7CcdCuF3bLajqaP6qMFERQFvzsRj9aeCCf3TNWXioLwwJAm"; + expectedChildren[9].wifPrivKey.n = 52; + // 10 + expectedChildren[10].path.p = "m/100"; + expectedChildren[10].path.n = 5; + expectedChildren[10].hexPubKey.p = "020db9ba00ddf68428e3f5bfe54252bbcd75b21e42f51bf3bfc4172bf0e5fa7905"; + expectedChildren[10].hexPubKey.n = 66; + expectedChildren[10].wifPrivKey.p = "L5ipKgExgKZYaxsQPEmyjrhoSepoxuSAxSWgK1GX5kaTUN3zGCU7"; + expectedChildren[10].wifPrivKey.n = 52; + // 11 + expectedChildren[11].path.p = "m/101"; + expectedChildren[11].path.n = 5; + expectedChildren[11].hexPubKey.p = "0299e3790956570737d6164e6fcda5a3daa304065ca95ba46bc73d436b84f34d46"; + expectedChildren[11].hexPubKey.n = 66; + expectedChildren[11].wifPrivKey.p = "L1iUjHWpYSead5vYZycMdMzCZDFQzveG3S6NviAi5BvvGdnuQbi6"; + expectedChildren[11].wifPrivKey.n = 52; + // 12 + expectedChildren[12].path.p = "m/102"; + expectedChildren[12].path.n = 5; + expectedChildren[12].hexPubKey.p = "0202e0732c4c5d2b1036af173640e01957998cfd4f9cdaefab6ffe76eb869e2c59"; + expectedChildren[12].hexPubKey.n = 66; + expectedChildren[12].wifPrivKey.p = "KybjnK4e985dgzxL5pgXTfq8YFagG8gB9HWAjLimagR4pdodCSNo"; + expectedChildren[12].wifPrivKey.n = 52; + // 13 + expectedChildren[13].path.p = "m/103"; + expectedChildren[13].path.n = 5; + expectedChildren[13].hexPubKey.p = "03d050adbd996c0c5d737ff638402dfbb8c08e451fef10e6d62fb57887c1ac6cb2"; + expectedChildren[13].hexPubKey.n = 66; + expectedChildren[13].wifPrivKey.p = "Kx9bf5cyf29fp7uuMVnqn47692xRwXStVmnL75w9i1sLQDjbFHP5"; + expectedChildren[13].wifPrivKey.n = 52; + // 14 + expectedChildren[14].path.p = "m/104"; + expectedChildren[14].path.n = 5; + expectedChildren[14].hexPubKey.p = "038d466399e2d68b4b16043ad4d88893b3b2f84fc443368729a973df1e66f4f530"; + expectedChildren[14].hexPubKey.n = 66; + expectedChildren[14].wifPrivKey.p = "L5myg7MNjKHcgVMS9ytmHgBftiWAi1awGpeC6p9dygsEQV9ZRvpz"; + expectedChildren[14].wifPrivKey.n = 52; + // 15 + expectedChildren[15].path.p = "m/105"; + expectedChildren[15].path.n = 5; + expectedChildren[15].hexPubKey.p = "034811e2f0c8c50440c08c2c9799b99c911c036e877e8325386ff61723ae3ffdce"; + expectedChildren[15].hexPubKey.n = 66; + expectedChildren[15].wifPrivKey.p = "L1KHrLBPhaJnvysjKUYk5QwkyWDb6uHgDM8EmE4eKtfqyJ13a7HC"; + expectedChildren[15].wifPrivKey.n = 52; + // 16 + expectedChildren[16].path.p = "m/106"; + expectedChildren[16].path.n = 5; + expectedChildren[16].hexPubKey.p = "026339fd5842921888e711a6ba9104a5f0c94cc0569855273cf5faefdfbcd3cc29"; + expectedChildren[16].hexPubKey.n = 66; + expectedChildren[16].wifPrivKey.p = "Kz4WPV43po7LRkatwHf9YGknGZRYfvo7TkvojinzxoFRXRYXyfDn"; + expectedChildren[16].wifPrivKey.n = 52; + // 17 + expectedChildren[17].path.p = "m/107"; + expectedChildren[17].path.n = 5; + expectedChildren[17].hexPubKey.p = "02833705c1069fab2aa92c6b0dac27807290d72e9f52378d493ac44849ca003b22"; + expectedChildren[17].hexPubKey.n = 66; + expectedChildren[17].wifPrivKey.p = "L3PxeN4w336kTk1becdFsAnR8ihh8SeMYXRHEzSmRNQTjtmcUjr9"; + expectedChildren[17].wifPrivKey.n = 52; + // 18 + expectedChildren[18].path.p = "m/108"; + expectedChildren[18].path.n = 5; + expectedChildren[18].hexPubKey.p = "032d2639bde1eb7bdf8444bd4f6cc26a9d1bdecd8ea15fac3b992c3da68d9d1df5"; + expectedChildren[18].hexPubKey.n = 66; + expectedChildren[18].wifPrivKey.p = "L2wf8FYiA888qrhDzHkFkZ3ZRBntysjtJa1QfcxE1eFiyDUZBRSi"; + expectedChildren[18].wifPrivKey.n = 52; + // 19 + expectedChildren[19].path.p = "m/109"; + expectedChildren[19].path.n = 5; + expectedChildren[19].hexPubKey.p = "02479c6d4a64b93a2f4343aa862c938fbc658c99219dd7bebb4830307cbd76c9e9"; + expectedChildren[19].hexPubKey.n = 66; + expectedChildren[19].wifPrivKey.p = "L5A5hcupWnYTNJTLTWDDfWyb3hnrJgdDgyN7c4PuF17bsY1tNjxS"; + expectedChildren[19].wifPrivKey.n = 52; + + for (size_t i = 0; i < 20; i++) { + testChildKey child = expectedChildren[i]; + Path__Handle path; + err = SKY_bip32_ParsePath(child.path, &path); + ck_assert_int_eq(err, SKY_OK); + GoInt len; + err = SKY_bip32_Path_Count(path, &len); + ck_assert_int_eq(err, SKY_OK); + ck_assert_int_eq(len, 2); + + PublicKey__Handle pubKey = 0; + bip32__PathNode element_tmp; + err = SKY_bip32_Path_GetElements(path, 1, &element_tmp); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_NewPublicChildKey(extendedMasterPublic, element_tmp.ChildNumber, &pubKey); + ck_assert_int_eq(err, SKY_OK); + GoUint8 buffer_pubkey_key_tmp[1024]; + GoSlice_ pubkey_key_tmp = {buffer_pubkey_key_tmp, 0, 1024}; + err = SKY_bip32_PublicKey_GetKey(pubKey, &pubkey_key_tmp); + ck_assert_int_eq(err, SKY_OK); + + GoString_ pubkey_hexpubkey; + GoSlice pubkey_key; + copyGoSlice_toGoSlice(&pubkey_key, &pubkey_key_tmp, pubkey_key_tmp.len); + err = SKY_base58_Hex2String(pubkey_key, &pubkey_hexpubkey); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isGoString_toGoStringEq(pubkey_hexpubkey, child.hexPubKey)); + + PublicKey__Handle pubKey2 = 0; + err = SKY_bip32_PrivateKey_NewPublicChildKey(extendedMasterPrivate, element_tmp.ChildNumber, &pubKey2); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isPublicKeyEq(pubKey, pubKey2)); + + PrivateKey__Handle privKey = 0; + err = SKY_bip32_PrivateKey_NewPrivateChildKey(extendedMasterPrivate, element_tmp.ChildNumber, &privKey); + ck_assert_int_eq(err, SKY_OK); + + cipher__SecKey expectedPrivKey; + err = SKY_cipher_SecKeyFromBitcoinWalletImportFormat(child.wifPrivKey, &expectedPrivKey); + ck_assert_int_eq(err, SKY_OK); + + PublicKey__Handle pubKey3 = 0; + err = SKY_bip32_PrivateKey_Publickey(privKey, &pubKey3); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isPublicKeyEq(pubKey, pubKey3)); + } +} +END_TEST + +START_TEST(TestMaxChildDepthError) +{ + printf("Load TestMaxChildDepthError \n"); + GoUint8 bufferTemp[1024]; + GoSlice tmp = {bufferTemp, 0, 1024}; + randBytes(&tmp, 32); + PrivateKey__Handle key = 0; + GoUint32 err = SKY_bip32_NewMasterKey(tmp, &key); + ck_assert_int_eq(err, SKY_OK); + GoUint8 reached = 0; + for (size_t i = 0; i < 256; i++) { + err = SKY_bip32_PrivateKey_NewPrivateChildKey(key, 0, &key); + switch (i) { + case 255: + ck_assert_int_eq(err, SKY_ErrMaxDepthReached); + reached = 1; + break; + + default: + ck_assert_int_eq(err, SKY_OK); + break; + } + } + ck_assert(reached == 1); +} +END_TEST + +typedef struct { + GoUint32 err; + GoString base58; +} tests_Struct; + + +START_TEST(TestDeserializePrivateInvalidStrings) +{ + printf("Load TestDeserializePrivateInvalidStrings\n"); + tests_Struct tests[MAXBUFFER]; + // 0 + tests[0].err = SKY_ErrSerializedKeyWrongSize; + tests[0].base58.p = "xprv9s21ZrQH143K4YUcKrp6cVxQaX59ZFkN6MFdeZjt8CHVYNs55xxQSvZpHWfojWMv6zgjmzopCyWPSFAnV4RU33J4pwCcnhsB4R4mPEnTsM"; + tests[0].base58.n = 110; + // 1 + tests[1].err = SKY_bip32_ErrInvalidChecksum; + tests[1].base58.p = "xprv9s21ZrQH143K3YSbAXLMPCzJso5QAarQksAGc5rQCyZCBfw4Rj2PqVLFNgezSBhktYkiL3Ta2stLPDF9yZtLMaxk6Spiqh3DNFG8p8MVeEc"; + tests[1].base58.n = 111; + // 2 + tests[2].err = SKY_ErrInvalidPrivateKeyVersion; + tests[2].base58.p = "xpub6DxSCdWu6jKqr4isjo7bsPeDD6s3J4YVQV1JSHZg12Eagdqnf7XX4fxqyW2sLhUoFWutL7tAELU2LiGZrEXtjVbvYptvTX5Eoa4Mamdjm9u"; + tests[2].base58.n = 111; + // 3 + tests[3].err = SKY_ErrInvalidKeyVersion; + tests[3].base58.p = "8FH81Rao5EgGmdScoN66TJAHsQP7phEMeyMTku9NBJd7hXgaj3HTvSNjqJjoqBpxdbuushwPEM5otvxXt2p9dcw33AqNKzZEPMqGHmz7Dpayi6Vb"; + tests[3].base58.n = 112; + // 4 + tests[4].err = SKY_bip32_ErrInvalidChecksum; + tests[4].base58.p = "xprvQQQQQQQQQQQQQQQQCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334"; + tests[4].base58.n = 111; + // 5 + tests[5].err = SKY_ErrSerializedKeyWrongSize; + tests[5].base58.p = "HAsbc6CgKmTYEQg2CTz7m5STEPAB"; + tests[5].base58.n = 28; + // 6 + tests[6].err = SKY_ErrInvalidFingerprint; + tests[6].base58.p = "xprv9tnJFvAXAXPfPnMTKfwpwnkty7MzJwELVgp4NTBquaKXy4RndyfJJCJJf7zNaVpBpzrwVRutZNLRCVLEcZHcvuCNG3zGbGBcZn57FbNnmSP"; + tests[6].base58.n = 111; + // 7 + tests[7].err = SKY_ErrInvalidPrivateKey; + tests[7].base58.p = "xprv9s21ZrQH143K3yLysFvsu3n1dMwhNusmNHr7xArzAeCc7MQYqDBBStmqnZq6WLi668siBBNs3SjiyaexduHu9sXT9ixTsqptL67ADqcaBdm"; + tests[7].base58.n = 111; + // 8 + tests[8].err = SKY_ErrInvalidChildNumber; + tests[8].base58.p = "xprv9s21ZrQYdgnodnKW4Drm1Qg7poU6Gf2WUDsjPxvYiK7iLBMrsjbnF1wsZZQgmXNeMSG3s7jmHk1b3JrzhG5w8mwXGxqFxfrweico7k8DtxR"; + tests[8].base58.n = 111; + // 9 + tests[9].err = SKY_ErrInvalidKeyVersion; + tests[9].base58.p = "1111111111111adADjFaSNPxwXqLjHLj4mBfYxuewDPbw9hEj1uaXCzMxRPXDFF3cUoezTFYom4sEmEVSQmENPPR315cFk9YUFVek73wE9"; + tests[9].base58.n = 106; + // 10 + tests[10].err = SKY_ErrSerializedKeyWrongSize; + tests[10].base58.p = "9XpNiB4DberdMn4jZiMhNGtuZUd7xUrCEGw4MG967zsVNvUKBEC9XLrmVmFasanWGp15zXfTNw4vW4KdvUAynEwyKjdho9QdLMPA2H5uyt"; + tests[10].base58.n = 106; + // 11 + tests[11].err = SKY_ErrSerializedKeyWrongSize; + tests[11].base58.p = "7JJikZQ2NUXjSAnAF2SjFYE3KXbnnVxzRBNddFE1DjbDEHVGEJzYC7zqSgPoauBJS3cWmZwsER94oYSFrW9vZ4Ch5FtGeifdzmtS3FGYDB1vxFZsYKgMc"; + tests[11].base58.n = 117; + + for (size_t i = 0; i < 12; i++) { + tests_Struct test = tests[i]; + GoUint8 bufferb[MAXBUFFER]; + GoSlice_ b_tmp = {bufferb, 0, MAXBUFFER}; + GoUint32 err = SKY_base58_Decode(test.base58, &b_tmp); + ck_assert_int_eq(err, SKY_OK); + + PrivateKey__Handle rest_priv = 0; + GoSlice b; + copyGoSlice_toGoSlice(&b, &b_tmp, b_tmp.len); + err = SKY_bip32_DeserializePrivateKey(b, &rest_priv); + ck_assert_int_eq(err, test.err); + } +} +END_TEST + +START_TEST(TestDeserializePublicInvalidStrings) +{ + printf("Load TestDeserializePublicInvalidStrings\n"); + tests_Struct tests[MAXBUFFER]; + // 0 + tests[0].err = SKY_ErrSerializedKeyWrongSize; + tests[0].base58.p = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet888"; + tests[0].base58.n = 113; + // 1 + tests[1].err = SKY_bip32_ErrInvalidChecksum; + tests[1].base58.p = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W11GMcet8"; + tests[1].base58.n = 111; + // 2 + tests[2].err = SKY_ErrInvalidPublicKeyVersion; + tests[2].base58.p = "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7"; + tests[2].base58.n = 111; + // 3 + tests[3].err = SKY_ErrInvalidFingerprint; + tests[3].base58.p = "xpub67tVq9SuNQCfm2PXBqjGRAtNZ935kx2uHJaURePth4JBpMfEy6jum7Euj7FTpbs7fnjhfZcNEktCucWHcJf74dbKLKNSTZCQozdDVwvkJhs"; + tests[3].base58.n = 111; + // 4 + tests[4].err = SKY_ErrInvalidChildNumber; + tests[4].base58.p = "xpub661MyMwTWkfYZq6BEh3ywGVXFvNj5hhzmWMhFBHSqmub31B1LZ9wbJ3DEYXZ8bHXGqnHKfepTud5a2XxGdnnePzZa2m2DyzTnFGBUXtaf9M"; + tests[4].base58.n = 111; + // 5 + tests[5].err = SKY_ErrInvalidPublicKey; + tests[5].base58.p = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gYymDsxxRe3WWeZQ7TadaLSdKUffezzczTCpB8j3JP96UwE2n6w1"; + tests[5].base58.n = 111; + // 6 + tests[6].err = SKY_ErrInvalidKeyVersion; + tests[6].base58.p = "8FH81Rao5EgGmdScoN66TJAHsQP7phEMeyMTku9NBJd7hXgaj3HTvSNjqJjoqBpxdbuushwPEM5otvxXt2p9dcw33AqNKzZEPMqGHmz7Dpayi6Vb"; + tests[6].base58.n = 112; + // 7 + tests[7].err = SKY_ErrInvalidKeyVersion; + tests[7].base58.p = "1111111111111adADjFaSNPxwXqLjHLj4mBfYxuewDPbw9hEj1uaXCzMxRPXDFF3cUoezTFYom4sEmEVSQmENPPR315cFk9YUFVek73wE9"; + tests[7].base58.n = 106; + // 8 + tests[8].err = SKY_ErrSerializedKeyWrongSize; + tests[8].base58.p = "7JJikZQ2NUXjSAnAF2SjFYE3KXbnnVxzRBNddFE1DjbDEHVGEJzYC7zqSgPoauBJS3cWmZwsER94oYSFrW9vZ4Ch5FtGeifdzmtS3FGYDB1vxFZsYKgMc"; + tests[8].base58.n = 117; + + for (size_t i = 0; i < 9; i++) { + tests_Struct test = tests[i]; + GoUint8 bufferb[MAXBUFFER]; + GoSlice_ b_tmp = {bufferb, 0, MAXBUFFER}; + GoUint32 err = SKY_base58_Decode(test.base58, &b_tmp); + ck_assert_msg(err == SKY_OK, " Iter %d", i); + + PublicKey__Handle rest_pub = 0; + GoSlice b; + copyGoSlice_toGoSlice(&b, &b_tmp, b_tmp.len); + err = SKY_bip32_DeserializePublicKey(b, &rest_pub); + ck_assert_msg(err == test.err, "Iter %d", i); + } +} +END_TEST + +START_TEST(TestCantCreateHardenedPublicChild) +{ + printf("Load TestCantCreateHardenedPublicChild\n"); + GoUint8 bufferb[MAXBUFFER]; + GoSlice b = {bufferb, 0, MAXBUFFER}; + randBytes(&b, 32); + PrivateKey__Handle key = 0; + GoUint32 err = SKY_bip32_NewMasterKey(b, &key); + ck_assert(err == SKY_OK); + + // Test that it works for private keys + PrivateKey__Handle priv_temp = 0; + err = SKY_bip32_PrivateKey_NewPrivateChildKey(key, FirstHardenedChild - 1, &priv_temp); + ck_assert(err == SKY_OK); + err = SKY_bip32_PrivateKey_NewPrivateChildKey(key, FirstHardenedChild, &priv_temp); + ck_assert(err == SKY_OK); + err = SKY_bip32_PrivateKey_NewPrivateChildKey(key, FirstHardenedChild + 1, &priv_temp); + ck_assert(err == SKY_OK); + + // Test that it throws an error for public keys if hardened + PublicKey__Handle pubkey = 0; + err = SKY_bip32_PrivateKey_Publickey(key, &pubkey); + ck_assert(err == SKY_OK); + + PublicKey__Handle pub_temp = 0; + err = SKY_bip32_PublicKey_NewPublicChildKey(pubkey, FirstHardenedChild - 1, &pub_temp); + ck_assert(err == SKY_OK); + err = SKY_bip32_PublicKey_NewPublicChildKey(pubkey, FirstHardenedChild, &pub_temp); + ck_assert_int_eq(err, SKY_ErrHardenedChildPublicKey); + err = SKY_bip32_PublicKey_NewPublicChildKey(pubkey, FirstHardenedChild + 1, &pub_temp); + ck_assert_int_eq(err, SKY_ErrHardenedChildPublicKey); +} +END_TEST + +typedef struct +{ + GoString seed; + GoString path; + GoString key; + GoUint32 err; +} cases_Str; + + +START_TEST(TestNewPrivateKeyFromPath) +{ + printf("Load TestNewPrivateKeyFromPath\n"); + cases_Str cases[MAXBUFFER]; + // 0 + cases[0].seed.p = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; + cases[0].seed.n = 52; + cases[0].path.p = "m"; + cases[0].path.n = 1; + cases[0].key.p = "xprv9s21ZrQH143K3GfuLFf1UxUB4GzmFav1hrzTG1bPorBTejryu4YfYVxZn6LNmwfvsi6uj1Wyv9vLDPsfKDuuqwEqYier1ZsbgWVd9NCieNv"; + cases[0].key.n = 111; + cases[0].err = SKY_OK; + // 1 + cases[1].seed.p = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; + cases[1].seed.n = 52; + cases[1].path.p = "m/1'"; + cases[1].path.n = 4; + cases[1].key.p = "xprv9uWf8oyvCHcAUg3kSjSroz67s7M3qJRWmNcdVwYGf91GFsaAatsVVp1bjH7z3WiWevqB7WK92B415oBwcahjoMvvb4mopPyqZUDeVW4168c"; + cases[1].key.n = 111; + cases[1].err = SKY_OK; + // 2 + cases[2].seed.p = "6162636465666768696A6B6C6D6E6F707172737475767778797A"; + cases[2].seed.n = 52; + cases[2].path.p = "m/1'/foo"; + cases[2].path.n = 8; + cases[2].key.p = ""; + cases[2].key.n = 0; + cases[2].err = SKY_ErrPathNodeNotNumber; + // 3 + cases[3].seed.p = "6162"; + cases[3].seed.n = 4; + cases[3].path.p = "m/1"; + cases[3].path.n = 3; + cases[3].key.p = ""; + cases[3].key.n = 0; + cases[3].err = SKY_ErrInvalidSeedLength; + + for (size_t i = 0; i < 4; i++) { + cases_Str tc = cases[i]; + GoUint8 bufferseed[MAXBUFFER]; + GoSlice_ seed_tmp = {bufferseed, 0, MAXBUFFER}; + GoUint32 err = SKY_base58_String2Hex(tc.seed, &seed_tmp); + ck_assert(err == SKY_OK); + + PrivateKey__Handle k = 0; + GoSlice seed; + copyGoSlice_toGoSlice(&seed, &seed_tmp, seed_tmp.len); + err = SKY_bip32_NewPrivateKeyFromPath(seed, tc.path, &k); + ck_assert(err == tc.err); + if (err == SKY_OK) { + GoUint8 bufferk_string[MAXBUFFER]; + GoString_ k_string = {bufferk_string, 0}; + err = SKY_bip32_PrivateKey_String(k, &k_string); + ck_assert(err == SKY_OK); + ck_assert(isGoString_toGoStringEq(k_string, tc.key)); + } + } +} +END_TEST +Suite* cipher_bip32(void) +{ + Suite* s = suite_create("Load cipher.bip32"); + TCase* tc; + + tc = tcase_create("cipher.bip32"); + tcase_add_checked_fixture(tc, setup, teardown); + tcase_add_test(tc, TestMaxChildDepthError); + tcase_add_test(tc, TestParentPublicChildDerivation); + tcase_add_test(tc, TestBip32TestVectors); + tcase_add_test(tc, TestDeserializePrivateInvalidStrings); + tcase_add_test(tc, TestDeserializePublicInvalidStrings); + tcase_add_test(tc, TestCantCreateHardenedPublicChild); + tcase_add_test(tc, TestNewPrivateKeyFromPath); + suite_add_tcase(s, tc); + tcase_set_timeout(tc, 150); + + return s; +} \ No newline at end of file diff --git a/lib/cgo/tests/check_cipher.bip44.bip44.c b/lib/cgo/tests/check_cipher.bip44.bip44.c new file mode 100644 index 000000000..541f4a067 --- /dev/null +++ b/lib/cgo/tests/check_cipher.bip44.bip44.c @@ -0,0 +1,186 @@ +#include +#include + +#include "libskycoin.h" +#include "skyerrors.h" +#include "skystring.h" +#include "skytest.h" +#include + +GoUint32 CoinTypeBitcoin = 0; +GoUint32 CoinTypeBitcoinTestnet = 1; +GoUint32 CoinTypeSkycoin = 8000; +GoUint32 ExternalChainIndex = 0; +GoUint32 ChangeChainIndex = 1; +GoUint32 FirstHardenedChild = 0x80000000; + +void mustDefaultSeed(GoSlice* seed) +{ + GoString mnemonic = {"dizzy cigar grant ramp inmate uniform gold success able payment faith practice", 78}; + GoString passphrase = {"", 0}; + GoUint8 bufferTmp[1024]; + GoSlice_ Tmp = {bufferTmp, 0, 1024}; + GoUint32 err = SKY_bip39_NewSeed(mnemonic, passphrase, &Tmp); + ck_assert_int_eq(err, SKY_OK); + copyGoSlice_toGoSlice(seed, &Tmp, sizeof(Tmp)); + GoUint8 strTmp[1024]; + GoString_ str = {strTmp, 0}; + err = SKY_base58_Hex2String(*seed, &str); + ck_assert_int_eq(err, SKY_OK); + ck_assert(strncmp(str.p, "24e563fb095d766df3862c70432cc1b2210b24d232da69af7af09d2ec86d28782ce58035bae29994c84081836aebe36a9b46af1578262fefc53e37efbe94be57", 128) == SKY_OK); +} + +START_TEST(TestNewCoin) +{ + // bad seed + GoUint8 bufferTmp[1024]; + GoSlice tmp = {bufferTmp, 0, 1024}; + randBytes(&tmp, 3); + Coin__Handle coin = 0; + GoUint32 err = SKY_bip44_NewCoin(tmp, CoinTypeBitcoin, &coin); + ck_assert_int_eq(err, SKY_ErrInvalidSeedLength); + // bad coin_type + GoUint8 bufferBad[1024]; + GoSlice Bad = {bufferBad, 0, 1024}; + mustDefaultSeed(&Bad); + err = SKY_bip44_NewCoin(Bad, FirstHardenedChild, &coin); + ck_assert_int_eq(err, SKY_ErrInvalidCoinType); + err = SKY_bip44_NewCoin(Bad, (FirstHardenedChild + 1), &coin); + ck_assert_int_eq(err, SKY_ErrInvalidCoinType); + + Coin__Handle c = 0; + err = SKY_bip44_NewCoin(Bad, CoinTypeBitcoin, &c); + ck_assert_int_eq(err, SKY_OK); + + Account__Handle account = 0; + err = SKY_bip44_Coin_Account(c, 0, &account); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferAccStr[1024]; + GoString acc_string = {bufferAccStr, 0}; + err = SKY_bip44_Account_String(account, &acc_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert_str_eq(acc_string.p, "xprv9yKAFQtFghZSe4mfdpdqFm1WWmGeQbYMB4MSGUB85zbKGQgSxty4duZb8k6hNoHVd2UR7Y3QhWU3rS9wox9ewgVG7gDLyYTL4yzEuqUCjvF"); + PrivateKey__Handle privk = 0; + PublicKey__Handle pubk = 0; + err = SKY_bip44_Account_GetPrivateKey(account, &privk); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_Publickey(privk, &pubk); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferPubKStr[1024]; + GoString pubk_string = {bufferPubKStr, 0}; + err = SKY_bip32_PublicKey_String(pubk, &pubk_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert_str_eq(pubk_string.p, "xpub6CJWevR9X57jrYr8jrAqctxF4o78p4GCYHH34rajeL8J9D1bWSHKBht4yzwiTQ4FP4HyQpx99iLxvU54rbEbcxBUgxzTGGudBVXb1N2gcHF"); + + err = SKY_bip44_Coin_Account(c, 1, &account); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip44_Account_String(account, &acc_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert_str_eq(acc_string.p, "xprv9yKAFQtFghZSgShGXkxHsYQfFaqMyutf3izng8tV4Tmp7gidQUPB8kCuv66yukidivM2oSaUvGus8ffnYvYKChB7DME2H2AvUq8LM2rXUzF"); + privk = 0; + pubk = 0; + err = SKY_bip44_Account_GetPrivateKey(account, &privk); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_Publickey(privk, &pubk); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_String(pubk, &pubk_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert_str_eq(pubk_string.p, "xpub6CJWevR9X57jtvmjdnVJEgMPocfrPNcWQwvPUXJ6coJnzV3mx1hRgYXPmQJh5vLQvrVCY8LtJB5xLLiPJVmpSwBe2yhonQLoQuSsCF8YPLN"); + + Account__Handle account_temp = 0; + err = SKY_bip44_Coin_Account(c, 0x80000000, &account_temp); + ck_assert_int_eq(err, SKY_ErrInvalidAccount); + err = SKY_bip44_Coin_Account(c, 0x80000001, &account_temp); + ck_assert_int_eq(err, SKY_ErrInvalidAccount); + + PrivateKey__Handle external = 0; + err = SKY_bip44_Account_External(account, &external); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferPrivKStr[1024]; + GoString privk_string = {bufferPrivKStr, 0}; + err = SKY_bip32_PrivateKey_String(external, &privk_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert_str_eq(privk_string.p, "xprv9zjsvjLiqSerDzbeRXPeXwz8tuQ7eRUABkgFAgLPHw1KzGKkgBhJhGaMYHM8j2KDXBZTCv4m19qjxrrD7gusrtdpZ7xzJywdXHaMZEjf3Uv"); + pubk = 0; + err = SKY_bip32_PrivateKey_Publickey(external, &pubk); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_String(pubk, &pubk_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert_str_eq(pubk_string.p, "xpub6DjELEscfpD9SUg7XYveu5vsSwEc3tC1Yybqy4jzrGYJs4euDj1ZF4tqPZYvViMn9cvBobHyubuuh69PZ1szaBBx5oxPiQzD492B6C4QDHe"); + + PublicKey__Handle external0 = 0; + err = SKY_bip32_PrivateKey_NewPublicChildKey(external, 0, &external0); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferKey[1024]; + GoUint8 bufferKeyStr[1024]; + GoSlice_ Key = {bufferKey, 0, 1024}; + GoString_ KeyStr = {bufferKeyStr, 0}; + err = SKY_bip32_PublicKey_GetKey(external0, &Key); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferKeySlice[1024]; + GoSlice KeySlice = {bufferKeySlice, 0, 1024}; + copyGoSlice_toGoSlice(&KeySlice, &Key, sizeof(Key)); + SKY_base58_Hex2String(KeySlice, &KeyStr); + ck_assert_str_eq(KeyStr.p, "034d36f3bcd74e19204e75b81b9c0726e41b799858b92bab73f4cd7498308c5c8b"); + + PublicKey__Handle external1 = 0; + err = SKY_bip32_PrivateKey_NewPublicChildKey(external, 1, &external1); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferKey1[1024]; + GoUint8 bufferKey1Str[1024]; + GoSlice_ Key1 = {bufferKey, 0, 1024}; + GoString_ Key1Str = {bufferKeyStr, 0}; + err = SKY_bip32_PublicKey_GetKey(external1, &Key1); + ck_assert_int_eq(err, SKY_OK); + GoUint8 bufferKey1Slice[1024]; + GoSlice Key1Slice = {bufferKey1Slice, 0, 1024}; + copyGoSlice_toGoSlice(&Key1Slice, &Key1, sizeof(Key1)); + SKY_base58_Hex2String(Key1Slice, &Key1Str); + ck_assert(strncmp(Key1Str.p, "02f7309e9f559d847ee9cc9ee144cfa490791e33e908fdbde2dade50a389408b01", 66) == 0); + + PrivateKey__Handle change = 0; + err = SKY_bip44_Account_Change(account, &change); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_String(change, &privk_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert(strncmp(privk_string.p, "xprv9zjsvjLiqSerGzJyBrpZgCaGpQCeFDnZEuAV714WigmFyHT4nFLhZLeuHzLNE19PgkZeQ5Uf2pjFZjQTHbkugDbmw5TAPAvgo2jsaTnZo2A", 66) == 0); + pubk = 0; + err = SKY_bip32_PrivateKey_Publickey(change, &pubk); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_String(pubk, &pubk_string); + ck_assert_int_eq(err, SKY_OK); + ck_assert(strncmp(pubk_string.p, "xpub6DjELEscfpD9VUPSHtMa3LX1NS38egWQc865uPU8H2JEr5nDKnex78yP9GxhFr5cnCRgiQF1dkv7aR7moraPrv73KHwSkDaXdWookR1Sh9p", 66) == 0); + + PublicKey__Handle change0 = 0; + err = SKY_bip32_PrivateKey_NewPublicChildKey(change, 0, &change0); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_GetKey(change0, &Key); + ck_assert_int_eq(err, SKY_OK); + copyGoSlice_toGoSlice(&KeySlice, &Key, sizeof(Key)); + SKY_base58_Hex2String(KeySlice, &KeyStr); + ck_assert(strncmp(KeyStr.p, "026d3eb891e81ecabedfa8560166af383457aedaf172af9d57d00508faa5f57c4c", 66) == 0); + + PublicKey__Handle change1 = 0; + err = SKY_bip32_PrivateKey_NewPublicChildKey(change, 1, &change1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_GetKey(change1, &Key1); + ck_assert_int_eq(err, SKY_OK); + copyGoSlice_toGoSlice(&Key1Slice, &Key1, sizeof(Key1)); + SKY_base58_Hex2String(Key1Slice, &Key1Str); + ck_assert(strncmp(Key1Str.p, "02681b301293fdf0292cd679b37d60b92a71b389fd994b2b57c8daf99532bfb4a5", 66) == 0); +} +END_TEST + +Suite* cipher_bip44(void) +{ + Suite* s = suite_create("Load cipher.bip44"); + TCase* tc; + + tc = tcase_create("cipher.bip44"); + tcase_add_checked_fixture(tc, setup, teardown); + tcase_add_test(tc, TestNewCoin); + suite_add_tcase(s, tc); + tcase_set_timeout(tc, 150); + + return s; +} \ No newline at end of file diff --git a/lib/cgo/tests/check_cipher.bitcoin.c b/lib/cgo/tests/check_cipher.bitcoin.c index 1023909b9..d86879dcc 100644 --- a/lib/cgo/tests/check_cipher.bitcoin.c +++ b/lib/cgo/tests/check_cipher.bitcoin.c @@ -1,9 +1,6 @@ - #include #include -//#include -//#include #include "libskycoin.h" #include "skyerrors.h" #include "skystring.h" @@ -43,18 +40,16 @@ START_TEST(TestBitcoinAddress) error = SKY_cipher_PubKeyFromHex(*pubKeyStr, &pubkey); ck_assert_msg(error == SKY_OK, "Create PubKey from Hex"); - GoString_ str = {NULL, 0}; + GoString str = {NULL, 0}; SKY_cipher_BitcoinAddressFromPubKey(&pubkey, &btcAddr); SKY_cipher_BitcoinAddress_String(&btcAddr, &str); - registerMemCleanup((void*)str.p); - GoString tmpStr = {str.p, str.n}; - ck_assert_str_eq(str.p, addrStr->p); + ck_assert(isGoStringEq(*addrStr, str)); error = SKY_cipher_BitcoinAddressFromSecKey(&seckey, &btcAddr); ck_assert(error == SKY_OK); GoString_ tmpstr = {buff, 0}; - SKY_cipher_BitcoinAddress_String(&btcAddr, &tmpstr); - ck_assert_str_eq(tmpStr.p, addrStr->p); + SKY_cipher_BitcoinAddress_String(&btcAddr, &str); + ck_assert(isGoStringEq(*addrStr, str)); } } END_TEST @@ -86,9 +81,9 @@ START_TEST(TestDecodeBase58BitcoinAddress) GoSlice b = {buffer_b, 0, 1024}; GoUint8 buffer_h_temp[1024]; GoString_ h_tmp = {buffer_h_temp, 0}; - coin__UxArray b_temp = {buffer_b_temp, 0, 1024}; + GoSlice_ b_temp = {buffer_b_temp, 0, 1024}; SKY_cipher_BitcoinAddress_Bytes(&a, &b_temp); - copycoin_UxArraytoGoSlice(&b, &b_temp, b_temp.len); + copyGoSlice_toGoSlice(&b, &b_temp, b_temp.len); GoInt_ len_b = b.len; b.len = (GoInt_)(len_b / 2); GoUint8_ buffer_h[1024]; @@ -100,9 +95,9 @@ START_TEST(TestDecodeBase58BitcoinAddress) err = SKY_cipher_DecodeBase58BitcoinAddress(h, &a2); ck_assert_int_ne(err, SKY_OK); - memset(&b_temp, 0, sizeof(coin__UxArray)); + memset(&b_temp, 0, sizeof(GoSlice_)); SKY_cipher_BitcoinAddress_Bytes(&a, &b_temp); - err = copycoin_UxArraytoGoSlice(&b, &b_temp, b_temp.len); + err = copyGoSlice_toGoSlice(&b, &b_temp, b_temp.len); ck_assert_int_eq(err, SKY_OK); err = SKY_base58_Hex2Base58(b, &h_tmp); ck_assert_int_eq(err, SKY_OK); @@ -235,28 +230,24 @@ START_TEST(TestBitcoinWIFRoundTrip) cipher__SecKey seckey; cipher__PubKey pubkey; SKY_cipher_GenerateKeyPair(&pubkey, &seckey); - unsigned char wip1_buff[50]; - unsigned char wip2_buff[50]; - GoString wip1; - GoString_ tmp_wip1 = {wip1_buff, 0}; - SKY_cipher_BitcoinWalletImportFormatFromSeckey(&seckey, &tmp_wip1); - wip1.n = tmp_wip1.n; - wip1.p = tmp_wip1.p; - registerMemCleanup((void*)wip1.p); + GoUint8 wip1_buff[50]; + GoUint8 wip2_buff[50]; + GoString wip1 = {wip1_buff, 0}; + SKY_cipher_BitcoinWalletImportFormatFromSeckey(&seckey, &wip1); cipher__SecKey seckey2; GoUint32 err; err = SKY_cipher_SecKeyFromBitcoinWalletImportFormat(wip1, &seckey2); ck_assert(err == SKY_OK); - GoString_ wip2; + GoString wip2 = {wip2_buff, 0}; SKY_cipher_BitcoinWalletImportFormatFromSeckey(&seckey2, &wip2); ck_assert(isSecKeyEq(&seckey, &seckey2)); - GoString_ seckeyhex1; - GoString_ seckeyhex2; + GoString seckeyhex1; + GoString seckeyhex2; SKY_cipher_SecKey_Hex(&seckey, &seckeyhex1); SKY_cipher_SecKey_Hex(&seckey2, &seckeyhex2); - ck_assert_str_eq((seckeyhex1.p), (seckeyhex2.p)); - ck_assert_str_eq((tmp_wip1.p), (wip2.p)); + ck_assert(isGoStringEq(seckeyhex1, seckeyhex2)); + ck_assert(isGoStringEq(wip1, wip2)); } END_TEST diff --git a/lib/cgo/tests/check_cipher.crypto.c b/lib/cgo/tests/check_cipher.crypto.c index bae0bf0a5..bf930e03c 100644 --- a/lib/cgo/tests/check_cipher.crypto.c +++ b/lib/cgo/tests/check_cipher.crypto.c @@ -7,167 +7,6 @@ #include "skytest.h" #include -START_TEST(TestNewPubKey) -{ - unsigned char buff[101]; - GoSlice slice; - cipher__PubKey pk, pk2; - cipher__SecKey sk; - - slice.data = buff; - slice.cap = 101; - - randBytes(&slice, 31); - slice.len = 31; - unsigned int errorcode = SKY_cipher_NewPubKey(slice, &pk); - ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "31 random bytes"); - - randBytes(&slice, 32); - errorcode = SKY_cipher_NewPubKey(slice, &pk); - ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "32 random bytes"); - - randBytes(&slice, 34); - errorcode = SKY_cipher_NewPubKey(slice, &pk); - ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "34 random bytes"); - - slice.len = 0; - errorcode = SKY_cipher_NewPubKey(slice, &pk); - ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "0 random bytes"); - - randBytes(&slice, 100); - errorcode = SKY_cipher_NewPubKey(slice, &pk); - ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "100 random bytes"); - - randBytes(&slice, 33); - errorcode = SKY_cipher_NewPubKey(slice, &pk); - ck_assert_msg(errorcode != SKY_OK, "33 random bytes"); - - SKY_cipher_GenerateKeyPair(&pk, &sk); - GoSlice buffer = {pk, sizeof(pk), sizeof(pk)}; - errorcode = SKY_cipher_NewPubKey(buffer, &pk2); - ck_assert_msg(errorcode == SKY_OK); - - ck_assert(isPubKeyEq(&pk, &pk2)); -} -END_TEST - -START_TEST(TestPubKeyFromHex) -{ - cipher__PubKey p, p1; - cipher__SecKey sk; - GoString s; - unsigned char buff[51]; - char sbuff[101]; - GoSlice slice = {(void*)buff, 0, 51}; - unsigned int errorcode; - - // Invalid hex - s.n = 0; - errorcode = SKY_cipher_PubKeyFromHex(s, &p1); - ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "TestPubKeyFromHex: Invalid hex. Empty string"); - - s.p = "cascs"; - s.n = strlen(s.p); - errorcode = SKY_cipher_PubKeyFromHex(s, &p1); - ck_assert_msg(errorcode == SKY_ErrInvalidPubKey, "TestPubKeyFromHex: Invalid hex. Bad chars"); - - // Invalid hex length - SKY_cipher_GenerateKeyPair(&p, &sk); - memcpy(slice.data, (void*)p, sizeof(p)); - slice.len = sizeof(p); - bytesnhex(&p[0], sbuff, slice.len >> 1); - s.p = sbuff; - s.n = strlen(s.p); - errorcode = SKY_cipher_PubKeyFromHex(s, &p1); - ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "TestPubKeyFromHex: Invalid hex length"); - - // Valid - bytesnhex(p, sbuff, sizeof(p)); - s.p = sbuff; - s.n = sizeof(p) << 1; - errorcode = SKY_cipher_PubKeyFromHex(s, &p1); - ck_assert_msg(errorcode == SKY_OK, "TestPubKeyFromHex: Valid. No panic."); - ck_assert(isPubKeyEq(&p, &p1)); -} -END_TEST - -START_TEST(TestPubKeyHex) -{ - cipher__PubKey p, p2; - cipher__SecKey sk; - GoString s3, s4; - unsigned char buff[50]; - unsigned char buff_s3[50]; - GoSlice slice = {buff, 0, 50}; - unsigned int errorcode; - - GoUint32 err = SKY_cipher_GenerateKeyPair(&p, &sk); - ck_assert(err == SKY_OK); - GoString_ tmp_s3 = {buff_s3, 0}; - err = SKY_cipher_PubKey_Hex(&p, &tmp_s3); - ck_assert(err == SKY_OK); - s3.n = tmp_s3.n; - s3.p = tmp_s3.p; - registerMemCleanup((void*)s3.p); - errorcode = SKY_cipher_PubKeyFromHex(s3, &p2); - ck_assert(errorcode == SKY_OK); - ck_assert(isPubKeyEq(&p, &p2)); - - unsigned char s4_buff[50]; - GoString_ tmp_s4 = {s4_buff, 0}; - err = SKY_cipher_PubKey_Hex(&p2, &tmp_s4); - ck_assert(err == SKY_OK); - s4.n = s4.n; - s4.p = s4.p; - registerMemCleanup((void*)s4.p); - // // TODO: Translate into cr_assert(eq(type(GoString), s3, s4)); - ck_assert(isGoStringEq(s3, s4) == 0); -} -END_TEST - -START_TEST(TestPubKeyVerify) -{ - cipher__PubKey p; - unsigned char buff[50]; - GoSlice slice = {buff, 0, 50}; - unsigned int errorcode; - int failed = 1; - - int i = 0; - for (; i < 10; i++) { - randBytes(&slice, 33); - memcpy((void*)&p, slice.data, 33); - failed = 1 || (errorcode = SKY_cipher_PubKey_Verify(&p)); - } - ck_assert(failed); -} -END_TEST - -START_TEST(TestPubKeyVerifyNil) -{ - cipher__PubKey p = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0}; - unsigned int errorcode; - - errorcode = SKY_cipher_PubKey_Verify(&p); - ck_assert(errorcode == SKY_ErrInvalidPubKey); -} -END_TEST - -START_TEST(TestPubKeyVerifyDefault1) -{ - cipher__PubKey p; - cipher__SecKey s; - - SKY_cipher_GenerateKeyPair(&p, &s); - GoUint32 errorcode = SKY_cipher_PubKey_Verify(&p); - ck_assert(errorcode == SKY_OK); -} -END_TEST - START_TEST(TestPubKeyVerifyDefault2) { cipher__PubKey p; @@ -218,34 +57,6 @@ START_TEST(TestPubKeyToAddress) } END_TEST -START_TEST(TestPubKeyToAddress2) -{ - cipher__PubKey p; - cipher__SecKey s; - cipher__Address addr; - GoString_ addrStr; - int i; - GoUint32 errorcode; - - for (i = 0; i < 1024; i++) { - SKY_cipher_GenerateKeyPair(&p, &s); - SKY_cipher_AddressFromPubKey(&p, &addr); - //func (self Address) Verify(key PubKey) error - errorcode = SKY_cipher_Address_Verify(&addr, &p); - ck_assert(errorcode == SKY_OK); - SKY_cipher_Address_String(&addr, &addrStr); - unsigned char buff[50]; - GoString addrStr_tmp = {buff, 0}; - addrStr_tmp.p = addrStr.p; - addrStr_tmp.n = addrStr.n; - registerMemCleanup((void*)addrStr.p); - errorcode = SKY_cipher_DecodeBase58Address(addrStr_tmp, &addr); - //func DecodeBase58Address(addr string) (Address, error) - ck_assert(errorcode == SKY_OK); - } -} -END_TEST - START_TEST(TestSecKeyFromHex) { unsigned char buff[50]; @@ -363,254 +174,6 @@ START_TEST(TestSecKeyVerify) } END_TEST -START_TEST(TestECDHonce) -{ - cipher__PubKey pub1, pub2; - cipher__SecKey sec1, sec2; - unsigned char buff1[50], buff2[50]; - GoSlice_ buf1, buf2; - - buf1.data = buff1; - buf1.len = 0; - buf1.cap = 50; - buf2.data = buff2; - buf2.len = 0; - buf2.cap = 50; - - SKY_cipher_GenerateKeyPair(&pub1, &sec1); - SKY_cipher_GenerateKeyPair(&pub2, &sec2); - - SKY_cipher_ECDH(&pub2, &sec1, &buf1); - SKY_cipher_ECDH(&pub1, &sec2, &buf2); - - // ECDH shared secrets are 32 bytes SHA256 hashes in the end - ck_assert(isSecKeyEq(&sec1, &sec2) == 0); - // ck_assert(eq(u8[32], buff1, buff2)); -} -END_TEST - -START_TEST(TestECDHloop) -{ - int i; - cipher__PubKey pub1, pub2; - cipher__SecKey sec1, sec2; - unsigned char buff1[50], buff2[50]; - GoSlice_ buf1, buf2; - - buf1.data = buff1; - buf1.len = 0; - buf1.cap = 50; - buf2.data = buff2; - buf2.len = 0; - buf2.cap = 50; - - for (i = 0; i < 128; i++) { - SKY_cipher_GenerateKeyPair(&pub1, &sec1); - SKY_cipher_GenerateKeyPair(&pub2, &sec2); - SKY_cipher_ECDH(&pub2, &sec1, &buf1); - SKY_cipher_ECDH(&pub1, &sec2, &buf2); - ck_assert_msg(isSecKeyEq(&sec1, &sec2) == 0, "Fail in %d", i); - } -} -END_TEST - -START_TEST(TestNewSig) -{ - unsigned char buff[101]; - GoSlice b; - cipher__Sig s; - int errorcode; - - b.data = buff; - b.len = 0; - b.cap = 101; - - randBytes(&b, 64); - errorcode = SKY_cipher_NewSig(b, &s); - ck_assert(errorcode == SKY_ErrInvalidLengthSig); - - randBytes(&b, 66); - errorcode = SKY_cipher_NewSig(b, &s); - ck_assert(errorcode == SKY_ErrInvalidLengthSig); - - randBytes(&b, 67); - errorcode = SKY_cipher_NewSig(b, &s); - ck_assert(errorcode == SKY_ErrInvalidLengthSig); - - randBytes(&b, 0); - errorcode = SKY_cipher_NewSig(b, &s); - ck_assert(errorcode == SKY_ErrInvalidLengthSig); - - randBytes(&b, 100); - errorcode = SKY_cipher_NewSig(b, &s); - ck_assert(errorcode == SKY_ErrInvalidLengthSig); - - randBytes(&b, 65); - errorcode = SKY_cipher_NewSig(b, &s); - ck_assert(errorcode == SKY_OK); - ck_assert(isU8Eq(buff, s, 65)); -} -END_TEST - -START_TEST(TestMustSigFromHex) -{ - unsigned char buff[101]; - char strBuff[257]; - GoSlice b = {buff, 0, 101}; - GoString str; - cipher__Sig s, s2; - int errorcode; - - // Invalid hex - str.p = ""; - str.n = strlen(str.p); - errorcode = SKY_cipher_SigFromHex(str, &s2); - ck_assert(errorcode == SKY_ErrInvalidLengthSig); - - str.p = "cascs"; - str.n = strlen(str.p); - errorcode = SKY_cipher_SigFromHex(str, &s2); - ck_assert(errorcode == SKY_ErrInvalidSig); - - // Invalid hex length - randBytes(&b, 65); - errorcode = SKY_cipher_NewSig(b, &s); - ck_assert(errorcode == SKY_OK); - str.p = strBuff; - str.n = 0; - bytesnhex(s, (char*)str.p, 32); - str.n = strlen(str.p); - errorcode = SKY_cipher_SigFromHex(str, &s2); - ck_assert(errorcode == SKY_ErrInvalidLengthSig); - - // Valid - bytesnhex(s, (char*)str.p, 65); - str.n = strlen(str.p); - errorcode = SKY_cipher_SigFromHex(str, &s2); - ck_assert(errorcode == SKY_OK); - ck_assert(isU8Eq(s2, s, 65)); -} -END_TEST - -START_TEST(TestSigHex) -{ - unsigned char buff[66]; - GoSlice b = {buff, 0, 66}; - char strBuff[150], - strBuff2[150]; - GoString str = {NULL, 0}, - str2 = {NULL, 0}; - cipher__Sig s, s2; - int errorcode; - - randBytes(&b, 65); - errorcode = SKY_cipher_NewSig(b, &s); - - ck_assert(errorcode == SKY_OK); - char buffer[100]; - GoString_ tmp_str = {buffer, 0}; - SKY_cipher_Sig_Hex(&s, &tmp_str); - str.p = tmp_str.p; - str.n = tmp_str.n; - registerMemCleanup((void*)str.p); - errorcode = SKY_cipher_SigFromHex(str, &s2); - - ck_assert(errorcode == SKY_OK); - ck_assert(isU8Eq(s, s2, 65)); - - char buffer2[100]; - GoString_ tmp_str2 = {buffer, 0}; - SKY_cipher_Sig_Hex(&s2, &tmp_str); - str2.p = tmp_str.p; - str2.n = tmp_str.n; - registerMemCleanup((void*)str2.p); - // ck_assert(isGoStringEq(str, str2)); - ck_assert_str_eq(str.p, str2.p); -} -END_TEST - -// FIXME: Split in multiple test cases so as to catch panic at the right place -START_TEST(TestVerifyAddressSignedHash) -{ - cipher__PubKey pk, pk2; - cipher__SecKey sk, sk2; - cipher__Address addr, addr2; - unsigned char buff[257]; - GoSlice b = {buff, 0, 257}; - cipher__SHA256 h, h2; - cipher__Sig sig, sig2; - int errorcode; - - SKY_cipher_GenerateKeyPair(&pk, &sk); - errorcode = SKY_cipher_PubKey_Verify(&pk); - ck_assert(errorcode == SKY_OK); - errorcode = SKY_cipher_SecKey_Verify(&sk); - ck_assert(errorcode == SKY_OK); - - SKY_cipher_AddressFromPubKey(&pk, &addr); - errorcode = SKY_cipher_Address_Verify(&addr, &pk); - ck_assert(errorcode == SKY_OK); - randBytes(&b, 256); - SKY_cipher_SumSHA256(b, &h); - SKY_cipher_SignHash(&h, &sk, &sig); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &h); - ck_assert(errorcode == SKY_OK); - - // Empty sig should be invalid - memset(&sig, 0, sizeof(sig)); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &h); - ck_assert(errorcode == SKY_ErrInvalidSigPubKeyRecovery); - - // Random sigs should not pass - int i; - for (i = 0; i < 100; i++) { - randBytes(&b, 65); - SKY_cipher_NewSig(b, &sig); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &h); - ck_assert(errorcode != SKY_OK); // One of many error codes - } - - // Sig for one hash does not work for another hash - randBytes(&b, 256); - SKY_cipher_SumSHA256(b, &h2); - SKY_cipher_SignHash(&h2, &sk, &sig2); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig2, &h2); - ck_assert(errorcode == SKY_OK); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig2, &h); - ck_assert(errorcode == SKY_ErrInvalidAddressForSig); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &h2); - ck_assert(errorcode != SKY_OK); // One of many error codes - - // Different secret keys should not create same sig - SKY_cipher_GenerateKeyPair(&pk2, &sk2); - SKY_cipher_AddressFromPubKey(&pk2, &addr2); - memset(&h, 0, sizeof(h)); - SKY_cipher_SignHash(&h, &sk, &sig); - SKY_cipher_SignHash(&h, &sk2, &sig2); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &h); - ck_assert(errorcode == SKY_OK); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr2, &sig2, &h); - ck_assert(errorcode == SKY_OK); - ck_assert_int_eq(isU8Eq(sig, sig2, 65), 0); - - randBytes(&b, 256); - SKY_cipher_SumSHA256(b, &h); - SKY_cipher_SignHash(&h, &sk, &sig); - SKY_cipher_SignHash(&h, &sk2, &sig2); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &h); - ck_assert(errorcode == SKY_OK); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr2, &sig2, &h); - ck_assert(errorcode == SKY_OK); - ck_assert_int_eq(isU8Eq(sig, sig2, 65), 0); - - // Bad address should be invalid - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr, &sig2, &h); - ck_assert(errorcode == SKY_ErrInvalidAddressForSig); - errorcode = SKY_cipher_VerifyAddressSignedHash(&addr2, &sig, &h); - ck_assert(errorcode == SKY_ErrInvalidAddressForSig); -} -END_TEST - START_TEST(TestSignHash) { cipher__PubKey pk, pk2; @@ -646,33 +209,6 @@ START_TEST(TestSignHash) } END_TEST -START_TEST(TestPubKeyFromSecKey) -{ - cipher__PubKey pk, pk2; - cipher__SecKey sk; - unsigned char buff[101]; - GoSlice b = {buff, 0, 101}; - int errorcode; - - SKY_cipher_GenerateKeyPair(&pk, &sk); - errorcode = SKY_cipher_PubKeyFromSecKey(&sk, &pk2); - ck_assert(errorcode == SKY_OK); - ck_assert(isU8Eq(pk, pk2, 33)); - - memset(&sk, 0, sizeof(sk)); - errorcode = SKY_cipher_PubKeyFromSecKey(&sk, &pk); - ck_assert(errorcode == SKY_ErrPubKeyFromNullSecKey); - - randBytes(&b, 99); - errorcode = SKY_cipher_NewSecKey(b, &sk); - ck_assert(errorcode == SKY_ErrInvalidLengthSecKey); - - randBytes(&b, 31); - errorcode = SKY_cipher_NewSecKey(b, &sk); - ck_assert(errorcode == SKY_ErrInvalidLengthSecKey); -} -END_TEST - START_TEST(TestPubKeyFromSig) { cipher__PubKey pk, pk2; @@ -812,6 +348,85 @@ START_TEST(TestSecKeyHashTest) } END_TEST +START_TEST(TestECDHonce) +{ + cipher__PubKey pub1, pub2; + cipher__SecKey sec1, sec2; + unsigned char buff1[50], buff2[50]; + GoSlice_ buf1, buf2; + + buf1.data = buff1; + buf1.len = 0; + buf1.cap = 50; + buf2.data = buff2; + buf2.len = 0; + buf2.cap = 50; + + SKY_cipher_GenerateKeyPair(&pub1, &sec1); + SKY_cipher_GenerateKeyPair(&pub2, &sec2); + + SKY_cipher_ECDH(&pub2, &sec1, &buf1); + SKY_cipher_ECDH(&pub1, &sec2, &buf2); + + // ECDH shared secrets are 32 bytes SHA256 hashes in the end + ck_assert(isSecKeyEq(&sec1, &sec2) == 0); + // ck_assert(eq(u8[32], buff1, buff2)); +} +END_TEST + +START_TEST(TestECDHloop) +{ + int i; + cipher__PubKey pub1, pub2; + cipher__SecKey sec1, sec2; + unsigned char buff1[50], buff2[50]; + GoSlice_ buf1, buf2; + + buf1.data = buff1; + buf1.len = 0; + buf1.cap = 50; + buf2.data = buff2; + buf2.len = 0; + buf2.cap = 50; + + for (i = 0; i < 128; i++) { + SKY_cipher_GenerateKeyPair(&pub1, &sec1); + SKY_cipher_GenerateKeyPair(&pub2, &sec2); + SKY_cipher_ECDH(&pub2, &sec1, &buf1); + SKY_cipher_ECDH(&pub1, &sec2, &buf2); + ck_assert_msg(isSecKeyEq(&sec1, &sec2) == 0, "Fail in %d", i); + } +} +END_TEST + +START_TEST(TestPubKeyToAddress2) +{ + cipher__PubKey p; + cipher__SecKey s; + cipher__Address addr; + GoString_ addrStr; + int i; + GoUint32 errorcode; + + for (i = 0; i < 1024; i++) { + SKY_cipher_GenerateKeyPair(&p, &s); + SKY_cipher_AddressFromPubKey(&p, &addr); + //func (self Address) Verify(key PubKey) error + errorcode = SKY_cipher_Address_Verify(&addr, &p); + ck_assert(errorcode == SKY_OK); + SKY_cipher_Address_String(&addr, &addrStr); + unsigned char buff[50]; + GoString addrStr_tmp = {buff, 0}; + addrStr_tmp.p = addrStr.p; + addrStr_tmp.n = addrStr.n; + registerMemCleanup((void*)addrStr.p); + errorcode = SKY_cipher_DecodeBase58Address(addrStr_tmp, &addr); + //func DecodeBase58Address(addr string) (Address, error) + ck_assert(errorcode == SKY_OK); + } +} +END_TEST + Suite* cipher_crypto(void) { Suite* s = suite_create("Load cipher.crypto"); @@ -819,32 +434,21 @@ Suite* cipher_crypto(void) tc = tcase_create("cipher.crypto"); tcase_add_checked_fixture(tc, setup, teardown); - tcase_add_test(tc, TestNewPubKey); - tcase_add_test(tc, TestPubKeyFromHex); - tcase_add_test(tc, TestPubKeyHex); - tcase_add_test(tc, TestPubKeyVerify); - tcase_add_test(tc, TestPubKeyVerifyNil); - tcase_add_test(tc, TestPubKeyVerifyDefault1); tcase_add_test(tc, TestPubKeyRipemd160); - tcase_add_test(tc, TestPubKeyToAddress2); tcase_add_test(tc, TestSecKeyFromHex); tcase_add_test(tc, TestMustSecKeyFromHex); tcase_add_test(tc, TestSecKeyVerify); - tcase_add_test(tc, TestECDHonce); - tcase_add_test(tc, TestECDHloop); - tcase_add_test(tc, TestNewSig); - tcase_add_test(tc, TestMustSigFromHex); - tcase_add_test(tc, TestSigHex); - tcase_add_test(tc, TestVerifyAddressSignedHash); - tcase_add_test(tc, TestPubKeyFromSecKey); tcase_add_test(tc, TestPubKeyFromSig); tcase_add_test(tc, TestVerifyPubKeySignedHash); tcase_add_test(tc, TestGenerateDeterministicKeyPair); tcase_add_test(tc, TestSecKeTest); tcase_add_test(tc, TestSecKeyHashTest); tcase_add_test(tc, TestGenerateKeyPair); + tcase_add_test(tc, TestECDHonce); + tcase_add_test(tc, TestECDHloop); + tcase_add_test(tc, TestPubKeyToAddress2); suite_add_tcase(s, tc); tcase_set_timeout(tc, 150); return s; -} \ No newline at end of file +} diff --git a/lib/cgo/tests/check_cipher.crypto.common.c b/lib/cgo/tests/check_cipher.crypto.common.c new file mode 100644 index 000000000..250fb064f --- /dev/null +++ b/lib/cgo/tests/check_cipher.crypto.common.c @@ -0,0 +1,335 @@ +#include +#include + +#include "libskycoin.h" +#include "skyassert.h" +#include "skyerrors.h" +#include "skystring.h" +#include "skytest.h" +#include + +START_TEST(TestNewPubKey) +{ + unsigned char buff[101]; + GoSlice slice; + cipher__PubKey pk, pk2; + cipher__SecKey sk; + + slice.data = buff; + slice.cap = 101; + + randBytes(&slice, 31); + slice.len = 31; + unsigned int errorcode = SKY_cipher_NewPubKey(slice, &pk); + ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "31 random bytes"); + + randBytes(&slice, 32); + errorcode = SKY_cipher_NewPubKey(slice, &pk); + ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "32 random bytes"); + + randBytes(&slice, 34); + errorcode = SKY_cipher_NewPubKey(slice, &pk); + ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "34 random bytes"); + + slice.len = 0; + errorcode = SKY_cipher_NewPubKey(slice, &pk); + ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "0 random bytes"); + + randBytes(&slice, 100); + errorcode = SKY_cipher_NewPubKey(slice, &pk); + ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "100 random bytes"); + + randBytes(&slice, 33); + errorcode = SKY_cipher_NewPubKey(slice, &pk); + ck_assert_msg(errorcode != SKY_OK, "33 random bytes"); + + SKY_cipher_GenerateKeyPair(&pk, &sk); + GoSlice buffer = {pk, sizeof(pk), sizeof(pk)}; + errorcode = SKY_cipher_NewPubKey(buffer, &pk2); + ck_assert_msg(errorcode == SKY_OK); + + ck_assert(isPubKeyEq(&pk, &pk2)); +} +END_TEST + +START_TEST(TestPubKeyFromHex) +{ + cipher__PubKey p, p1; + cipher__SecKey sk; + GoString s; + unsigned char buff[51]; + char sbuff[101]; + GoSlice slice = {(void*)buff, 0, 51}; + unsigned int errorcode; + + // Invalid hex + s.n = 0; + errorcode = SKY_cipher_PubKeyFromHex(s, &p1); + ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "TestPubKeyFromHex: Invalid hex. Empty string"); + + s.p = "cascs"; + s.n = strlen(s.p); + errorcode = SKY_cipher_PubKeyFromHex(s, &p1); + ck_assert_msg(errorcode == SKY_ErrInvalidPubKey, "TestPubKeyFromHex: Invalid hex. Bad chars"); + + // Invalid hex length + SKY_cipher_GenerateKeyPair(&p, &sk); + memcpy(slice.data, (void*)p, sizeof(p)); + slice.len = sizeof(p); + bytesnhex(&p[0], sbuff, slice.len >> 1); + s.p = sbuff; + s.n = strlen(s.p); + errorcode = SKY_cipher_PubKeyFromHex(s, &p1); + ck_assert_msg(errorcode == SKY_ErrInvalidLengthPubKey, "TestPubKeyFromHex: Invalid hex length"); + + // Valid + bytesnhex(p, sbuff, sizeof(p)); + s.p = sbuff; + s.n = sizeof(p) << 1; + errorcode = SKY_cipher_PubKeyFromHex(s, &p1); + ck_assert_msg(errorcode == SKY_OK, "TestPubKeyFromHex: Valid. No panic."); + ck_assert(isPubKeyEq(&p, &p1)); +} +END_TEST + +START_TEST(TestPubKeyHex) +{ + cipher__PubKey p, p2; + cipher__SecKey sk; + GoString s3, s4; + unsigned char buff[50]; + unsigned char buff_s3[50]; + GoSlice slice = {buff, 0, 50}; + unsigned int errorcode; + + GoUint32 err = SKY_cipher_GenerateKeyPair(&p, &sk); + ck_assert(err == SKY_OK); + GoString tmp_s3 = {buff_s3, 0}; + err = SKY_cipher_PubKey_Hex(&p, &tmp_s3); + ck_assert(err == SKY_OK); + s3.n = tmp_s3.n; + s3.p = tmp_s3.p; + registerMemCleanup((void*)s3.p); + errorcode = SKY_cipher_PubKeyFromHex(s3, &p2); + ck_assert(errorcode == SKY_OK); + ck_assert(isPubKeyEq(&p, &p2)); + + unsigned char s4_buff[50]; + GoString tmp_s4 = {s4_buff, 0}; + err = SKY_cipher_PubKey_Hex(&p2, &tmp_s4); + ck_assert(err == SKY_OK); + s4.n = s4.n; + s4.p = s4.p; + registerMemCleanup((void*)s4.p); + // // TODO: Translate into cr_assert(eq(type(GoString), s3, s4)); + ck_assert(isGoStringEq(s3, s4) == 0); +} +END_TEST + +START_TEST(TestPubKeyVerify) +{ + cipher__PubKey p; + unsigned char buff[50]; + GoSlice slice = {buff, 0, 50}; + unsigned int errorcode; + int failed = 1; + + int i = 0; + for (; i < 10; i++) { + randBytes(&slice, 33); + memcpy((void*)&p, slice.data, 33); + failed = 1 || (errorcode = SKY_cipher_PubKey_Verify(&p)); + } + ck_assert(failed); +} +END_TEST + +START_TEST(TestPubKeyVerifyNil) +{ + cipher__PubKey p = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0}; + unsigned int errorcode; + + errorcode = SKY_cipher_PubKey_Verify(&p); + ck_assert(errorcode == SKY_ErrInvalidPubKey); +} +END_TEST + +START_TEST(TestPubKeyVerifyDefault1) +{ + cipher__PubKey p; + cipher__SecKey s; + + SKY_cipher_GenerateKeyPair(&p, &s); + GoUint32 errorcode = SKY_cipher_PubKey_Verify(&p); + ck_assert(errorcode == SKY_OK); +} +END_TEST + +START_TEST(TestNewSig) +{ + unsigned char buff[101]; + GoSlice b; + cipher__Sig s; + int errorcode; + + b.data = buff; + b.len = 0; + b.cap = 101; + + randBytes(&b, 64); + errorcode = SKY_cipher_NewSig(b, &s); + ck_assert(errorcode == SKY_ErrInvalidLengthSig); + + randBytes(&b, 66); + errorcode = SKY_cipher_NewSig(b, &s); + ck_assert(errorcode == SKY_ErrInvalidLengthSig); + + randBytes(&b, 67); + errorcode = SKY_cipher_NewSig(b, &s); + ck_assert(errorcode == SKY_ErrInvalidLengthSig); + + randBytes(&b, 0); + errorcode = SKY_cipher_NewSig(b, &s); + ck_assert(errorcode == SKY_ErrInvalidLengthSig); + + randBytes(&b, 100); + errorcode = SKY_cipher_NewSig(b, &s); + ck_assert(errorcode == SKY_ErrInvalidLengthSig); + + randBytes(&b, 65); + errorcode = SKY_cipher_NewSig(b, &s); + ck_assert(errorcode == SKY_OK); + ck_assert(isU8Eq(buff, s, 65)); +} +END_TEST + +START_TEST(TestMustSigFromHex) +{ + unsigned char buff[101]; + char strBuff[257]; + GoSlice b = {buff, 0, 101}; + GoString str; + cipher__Sig s, s2; + int errorcode; + + // Invalid hex + str.p = ""; + str.n = strlen(str.p); + errorcode = SKY_cipher_SigFromHex(str, &s2); + ck_assert(errorcode == SKY_ErrInvalidLengthSig); + + str.p = "cascs"; + str.n = strlen(str.p); + errorcode = SKY_cipher_SigFromHex(str, &s2); + ck_assert(errorcode == SKY_ErrInvalidSig); + + // Invalid hex length + randBytes(&b, 65); + errorcode = SKY_cipher_NewSig(b, &s); + ck_assert(errorcode == SKY_OK); + str.p = strBuff; + str.n = 0; + bytesnhex(s, (char*)str.p, 32); + str.n = strlen(str.p); + errorcode = SKY_cipher_SigFromHex(str, &s2); + ck_assert(errorcode == SKY_ErrInvalidLengthSig); + + // Valid + bytesnhex(s, (char*)str.p, 65); + str.n = strlen(str.p); + errorcode = SKY_cipher_SigFromHex(str, &s2); + ck_assert(errorcode == SKY_OK); + ck_assert(isU8Eq(s2, s, 65)); +} +END_TEST + +START_TEST(TestSigHex) +{ + unsigned char buff[66]; + GoSlice b = {buff, 0, 66}; + char strBuff[150], + strBuff2[150]; + GoString str = {NULL, 0}, + str2 = {NULL, 0}; + cipher__Sig s, s2; + int errorcode; + + randBytes(&b, 65); + errorcode = SKY_cipher_NewSig(b, &s); + + ck_assert(errorcode == SKY_OK); + char buffer[100]; + GoString tmp_str = {buffer, 0}; + SKY_cipher_Sig_Hex(&s, &tmp_str); + str.p = tmp_str.p; + str.n = tmp_str.n; + registerMemCleanup((void*)str.p); + errorcode = SKY_cipher_SigFromHex(str, &s2); + + ck_assert(errorcode == SKY_OK); + ck_assert(isU8Eq(s, s2, 65)); + + char buffer2[100]; + GoString_ tmp_str2 = {buffer, 0}; + SKY_cipher_Sig_Hex(&s2, &tmp_str); + str2.p = tmp_str.p; + str2.n = tmp_str.n; + registerMemCleanup((void*)str2.p); + // ck_assert(isGoStringEq(str, str2)); + ck_assert_str_eq(str.p, str2.p); +} +END_TEST + +START_TEST(TestPubKeyFromSecKey) +{ + cipher__PubKey pk, pk2; + cipher__SecKey sk; + unsigned char buff[101]; + GoSlice b = {buff, 0, 101}; + int errorcode; + + SKY_cipher_GenerateKeyPair(&pk, &sk); + errorcode = SKY_cipher_PubKeyFromSecKey(&sk, &pk2); + ck_assert(errorcode == SKY_OK); + ck_assert(isU8Eq(pk, pk2, 33)); + + memset(&sk, 0, sizeof(sk)); + errorcode = SKY_cipher_PubKeyFromSecKey(&sk, &pk); + ck_assert(errorcode == SKY_ErrPubKeyFromNullSecKey); + + randBytes(&b, 99); + errorcode = SKY_cipher_NewSecKey(b, &sk); + ck_assert(errorcode == SKY_ErrInvalidLengthSecKey); + + randBytes(&b, 31); + errorcode = SKY_cipher_NewSecKey(b, &sk); + ck_assert(errorcode == SKY_ErrInvalidLengthSecKey); +} +END_TEST + +// define test suite and cases +Suite* common_check_cipher_crypto(void) +{ + Suite* s = suite_create("Load common check_cipher.crypto"); + TCase* tc; + + tc = tcase_create("check_cipher.crypto"); + tcase_add_test(tc, TestNewPubKey); + tcase_add_test(tc, TestPubKeyFromHex); + tcase_add_test(tc, TestPubKeyHex); + tcase_add_test(tc, TestPubKeyVerify); + tcase_add_test(tc, TestPubKeyVerifyNil); + tcase_add_test(tc, TestPubKeyVerifyDefault1); + tcase_add_test(tc, TestNewSig); + tcase_add_test(tc, TestMustSigFromHex); + tcase_add_test(tc, TestSigHex); + tcase_add_test(tc, TestPubKeyFromSecKey); + suite_add_tcase(s, tc); + tcase_set_timeout(tc, 150); + + return s; +} diff --git a/lib/cgo/tests/check_cipher.encrypt.scrypt_chacha20poly1305.c b/lib/cgo/tests/check_cipher.encrypt.scrypt_chacha20poly1305.c index 7671d25f1..448debf11 100644 --- a/lib/cgo/tests/check_cipher.encrypt.scrypt_chacha20poly1305.c +++ b/lib/cgo/tests/check_cipher.encrypt.scrypt_chacha20poly1305.c @@ -143,7 +143,7 @@ END_TEST START_TEST(TestScryptChacha20poly1305Decrypt) { - coin__UxArray result; + GoSlice_ result; GoSlice nullData; GoSlice nullPassword; GoSlice_ text; diff --git a/lib/cgo/tests/check_cipher.hash.c b/lib/cgo/tests/check_cipher.hash.c index 9689c2437..46d2e88bd 100644 --- a/lib/cgo/tests/check_cipher.hash.c +++ b/lib/cgo/tests/check_cipher.hash.c @@ -8,50 +8,44 @@ #include "skytest.h" #include -void freshSumRipemd160(GoSlice bytes, cipher__Ripemd160* rp160) -{ - SKY_cipher_HashRipemd160(bytes, rp160); -} +extern void freshSumSHA256(GoSlice bytes, cipher__SHA256* sha256); -void freshSumSHA256(GoSlice bytes, cipher__SHA256* sha256) -{ - SKY_cipher_SumSHA256(bytes, sha256); -} -START_TEST(TestHashRipemd160) +START_TEST(TestSumSHA256) { - cipher__Ripemd160 tmp; - cipher__Ripemd160 r; - cipher__Ripemd160 r2; - unsigned char buff[257]; - GoSlice slice = {buff, 0, 257}; - - randBytes(&slice, 128); - SKY_cipher_HashRipemd160(slice, &tmp); - randBytes(&slice, 160); - SKY_cipher_HashRipemd160(slice, &r); - ck_assert_int_eq(isU8Eq(tmp, r, sizeof(cipher__Ripemd160)), 0); - - unsigned char buff1[257]; - GoSlice b = {buff1, 0, 257}; + printf("Load TestSumSHA256 \n"); + GoUint8 bbuff[257]; + GoUint8 cbuff[257]; + GoSlice b = {bbuff, 0, 257}; + GoSlice_ b_tmp = {bbuff, 0, 257}; + cipher__SHA256 h1; randBytes(&b, 256); - SKY_cipher_HashRipemd160(b, &r2); - ck_assert_int_eq(isU8Eq(tmp, r2, sizeof(cipher__Ripemd160)), 0); - freshSumRipemd160(b, &tmp); - ck_assert(isU8Eq(tmp, r2, sizeof(cipher__Ripemd160))); + SKY_cipher_SumSHA256(b, &h1); + cipher__SHA256 tmp = ""; + ck_assert_int_eq(isU8Eq(h1, tmp, 32), 0); + GoSlice c = {cbuff, 0, 257}; + randBytes(&c, 256); + cipher__SHA256 h2; + SKY_cipher_SumSHA256(c, &h2); + ck_assert_int_eq(isU8Eq(h1, tmp, 32), 0); + cipher__SHA256 tmp_h2; + freshSumSHA256(c, &tmp_h2); + ck_assert(isU8Eq(h2, tmp_h2, 32)); } END_TEST START_TEST(TestRipemd160Set) { + printf("Load TestRipemd160Set \n"); cipher__Ripemd160 h; unsigned char buff[101]; GoSlice slice = {buff, 0, 101}; + GoSlice_ slice_tmp = {buff, 0, 101}; int error; memset(h, 0, sizeof(cipher__Ripemd160)); - randBytes(&slice, 21); + randBytes(&slice, 21); error = SKY_cipher_Ripemd160_Set(&h, slice); ck_assert(error == SKY_ErrInvalidLengthRipemd160); @@ -74,164 +68,9 @@ START_TEST(TestRipemd160Set) } END_TEST -START_TEST(TestSHA256Set) -{ - cipher__SHA256 h; - unsigned char buff[101]; - GoSlice slice = {buff, 0, 101}; - int error; - - randBytes(&slice, 33); - error = SKY_cipher_SHA256_Set(&h, slice); - ck_assert(error == SKY_ErrInvalidLengthSHA256); - - randBytes(&slice, 100); - error = SKY_cipher_SHA256_Set(&h, slice); - ck_assert(error == SKY_ErrInvalidLengthSHA256); - - randBytes(&slice, 31); - error = SKY_cipher_SHA256_Set(&h, slice); - ck_assert(error == SKY_ErrInvalidLengthSHA256); - - randBytes(&slice, 0); - error = SKY_cipher_SHA256_Set(&h, slice); - ck_assert(error == SKY_ErrInvalidLengthSHA256); - - randBytes(&slice, 32); - error = SKY_cipher_SHA256_Set(&h, slice); - ck_assert(error == SKY_OK); - ck_assert(isU8Eq(h, slice.data, 32)); -} -END_TEST - -START_TEST(TestSHA256Hex) -{ - cipher__SHA256 h; - unsigned char buff[101]; - GoSlice slice = {buff, 0, 101}; - int error; - - memset(&h, 0, sizeof(h)); - randBytes(&slice, 32); - SKY_cipher_SHA256_Set(&h, slice); - GoString_ s; - - SKY_cipher_SHA256_Hex(&h, &s); - registerMemCleanup((void*)s.p); - - cipher__SHA256 h2; - GoString tmpS = {s.p, s.n}; - error = SKY_cipher_SHA256FromHex(tmpS, &h2); - ck_assert(error == SKY_OK); - ck_assert(isU8Eq(h, h2, 32)); - - GoString_ s2; - SKY_cipher_SHA256_Hex(&h2, &s2); - registerMemCleanup((void*)s2.p); - ck_assert_str_eq(s.p, s2.p); -} -END_TEST - -START_TEST(TestSHA256KnownValue) -{ - typedef struct - { - char* input; - char* output; - } tmpstruct; - - tmpstruct vals[3]; - - vals[0].input = "skycoin"; - vals[0].output = - "5a42c0643bdb465d90bf673b99c14f5fa02db71513249d904573d2b8b63d353d"; - - vals[1].input = "hello world"; - vals[1].output = - "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; - - vals[2].input = "hello world asd awd awd awdapodawpokawpod "; - vals[2].output = - "99d71f95cafe05ea2dddebc35b6083bd5af0e44850c9dc5139b4476c99950be4"; - int i; - for (i = 0; i < 3; ++i) { - GoSlice slice_input; - GoSlice slice_output; - - slice_input.data = vals[i].input; - slice_input.len = strlen(vals[i].input); - slice_input.cap = strlen(vals[i].input) + 1; - - cipher__SHA256 sha; - - SKY_cipher_SumSHA256(slice_input, &sha); - - GoString_ tmp_output; - - SKY_cipher_SHA256_Hex(&sha, &tmp_output); - registerMemCleanup((void*)tmp_output.p); - - ck_assert(strcmp(tmp_output.p, vals[i].output) == SKY_OK); - } -} -END_TEST - -START_TEST(TestSumSHA256) -{ - GoUint8 bbuff[257]; - GoUint8 cbuff[257]; - GoSlice b = {bbuff, 0, 257}; - cipher__SHA256 h1; - randBytes(&b, 256); - SKY_cipher_SumSHA256(b, &h1); - cipher__SHA256 tmp = ""; - ck_assert_int_eq(isU8Eq(h1, tmp, 32), 0); - GoSlice c = {cbuff, 0, 257}; - randBytes(&c, 256); - cipher__SHA256 h2; - SKY_cipher_SumSHA256(c, &h2); - ck_assert_int_eq(isU8Eq(h1, tmp, 32), 0); - cipher__SHA256 tmp_h2; - freshSumSHA256(c, &tmp_h2); - ck_assert(isU8Eq(h2, tmp_h2, 32)); -} -END_TEST - -START_TEST(TestSHA256FromHex) -{ - unsigned int error; - cipher__SHA256 tmp; - // Invalid hex hash - GoString tmp_string = {"cawcd", 5}; - error = SKY_cipher_SHA256FromHex(tmp_string, &tmp); - ck_assert(error == SKY_ERROR); - // Truncated hex hash - cipher__SHA256 h; - unsigned char buff[130]; - char sbuff[300]; - GoSlice slice = {buff, 0, 130}; - randBytes(&slice, 128); - SKY_cipher_SumSHA256(slice, &h); - bytesnhex(h, sbuff, sizeof(h) >> 1); - GoString s1 = {sbuff, strlen(sbuff)}; - error = SKY_cipher_SHA256FromHex(s1, &h); - ck_assert(error == SKY_ErrInvalidHexLength); - - // Valid hex hash - GoString_ s2; - memset(&s2, 0, sizeof(GoString_)); - SKY_cipher_SHA256_Hex(&h, &s2); - registerMemCleanup((void*)s2.p); - cipher__SHA256 h2; - GoString tmps2 = {s2.p, s2.n}; - error = SKY_cipher_SHA256FromHex(tmps2, &h2); - ck_assert(error == SKY_OK); - ck_assert(isU8Eq(h, h2, 32)); -} -END_TEST - START_TEST(TestDoubleSHA256) { + printf("Load TestDoubleSHA256\n"); unsigned char bbuff[130]; GoSlice b = {bbuff, 0, 130}; randBytes(&b, 128); @@ -244,32 +83,9 @@ START_TEST(TestDoubleSHA256) } END_TEST -START_TEST(TestAddSHA256) -{ - unsigned char bbuff[130]; - GoSlice b = {bbuff, 0, 130}; - randBytes(&b, 128); - cipher__SHA256 h; - SKY_cipher_SumSHA256(b, &h); - - unsigned char cbuff[130]; - GoSlice c = {cbuff, 0, 130}; - randBytes(&c, 64); - cipher__SHA256 i; - SKY_cipher_SumSHA256(c, &i); - - cipher__SHA256 add; - cipher__SHA256 tmp; - - SKY_cipher_AddSHA256(&h, &i, &add); - ck_assert_int_eq(isU8Eq(add, tmp, 32), 0); - ck_assert_int_eq(isU8Eq(add, h, 32), 0); - ck_assert_int_eq(isU8Eq(add, i, 32), 0); -} -END_TEST - START_TEST(TestXorSHA256) { + printf("Load TestXorSHA256 \n"); unsigned char bbuff[129], cbuff[129]; GoSlice b = {bbuff, 0, 129}; GoSlice c = {cbuff, 0, 129}; @@ -295,6 +111,7 @@ END_TEST START_TEST(TestMerkle) { + printf("Load TestMerkle \n"); unsigned char buff[129]; cipher__SHA256 hashlist[5]; GoSlice b = {buff, 0, 129}, hashes = {hashlist, 0, 5}; @@ -349,23 +166,6 @@ START_TEST(TestMerkle) } END_TEST -START_TEST(TestSHA256Null) -{ - cipher__SHA256 x; - memset(&x, 0, sizeof(cipher__SHA256)); - GoUint32 result; - GoUint8 isNull; - ck_assert(SKY_cipher_SHA256_Null(&x, &isNull) == SKY_OK); - ck_assert(isNull); - char buff[130]; - GoSlice b = {buff, 0, 129}; - randBytes(&b, 128); - ck_assert(SKY_cipher_SumSHA256(b, &x) == SKY_OK); - ck_assert(SKY_cipher_SHA256_Null(&x, &isNull) == SKY_OK); - ck_assert(isNull == 0); -} -END_TEST - Suite* cipher_hash(void) { Suite* s = suite_create("Load cipher.hash"); @@ -373,18 +173,11 @@ Suite* cipher_hash(void) tc = tcase_create("cipher.hash"); tcase_add_checked_fixture(tc, setup, teardown); - tcase_add_test(tc, TestHashRipemd160); - tcase_add_test(tc, TestRipemd160Set); - tcase_add_test(tc, TestSHA256Set); - tcase_add_test(tc, TestSHA256Hex); - tcase_add_test(tc, TestSHA256KnownValue); tcase_add_test(tc, TestSumSHA256); - tcase_add_test(tc, TestSHA256FromHex); + tcase_add_test(tc, TestRipemd160Set); tcase_add_test(tc, TestDoubleSHA256); - tcase_add_test(tc, TestAddSHA256); tcase_add_test(tc, TestXorSHA256); tcase_add_test(tc, TestMerkle); - tcase_add_test(tc, TestSHA256Null); suite_add_tcase(s, tc); tcase_set_timeout(tc, 150); diff --git a/lib/cgo/tests/check_cipher.hash.common.c b/lib/cgo/tests/check_cipher.hash.common.c new file mode 100644 index 000000000..295d8f128 --- /dev/null +++ b/lib/cgo/tests/check_cipher.hash.common.c @@ -0,0 +1,216 @@ +#include +#include + +#include "libskycoin.h" +#include "skyassert.h" +#include "skyerrors.h" +#include "skystring.h" +#include "skytest.h" +#include + + +void freshSumRipemd160(GoSlice bytes, cipher__Ripemd160* rp160) +{ + SKY_cipher_HashRipemd160(bytes, rp160); +} + +void freshSumSHA256(GoSlice bytes, cipher__SHA256* sha256) +{ + SKY_cipher_SumSHA256(bytes, sha256); +} + +START_TEST(TestAddSHA256) +{ + printf("Load TestAddSHA256 \n"); + unsigned char bbuff[130]; + GoSlice b = {bbuff, 0, 130}; + randBytes(&b, 128); + cipher__SHA256 h; + SKY_cipher_SumSHA256(b, &h); + + unsigned char cbuff[130]; + GoSlice c = {cbuff, 0, 130}; + randBytes(&c, 64); + cipher__SHA256 i; + SKY_cipher_SumSHA256(c, &i); + + cipher__SHA256 add; + cipher__SHA256 tmp; + + SKY_cipher_AddSHA256(&h, &i, &add); + ck_assert_int_eq(isU8Eq(add, tmp, 32), 0); + ck_assert_int_eq(isU8Eq(add, h, 32), 0); + ck_assert_int_eq(isU8Eq(add, i, 32), 0); +} +END_TEST + +START_TEST(TestHashRipemd160) +{ + printf("Load TestHashRipemd160\n"); + cipher__Ripemd160 tmp; + cipher__Ripemd160 r; + cipher__Ripemd160 r2; + unsigned char buff[257]; + GoSlice slice = {buff, 0, 257}; + + randBytes(&slice, 128); + SKY_cipher_HashRipemd160(slice, &tmp); + randBytes(&slice, 160); + SKY_cipher_HashRipemd160(slice, &r); + ck_assert_int_eq(isU8Eq(tmp, r, sizeof(cipher__Ripemd160)), 0); + + unsigned char buff1[257]; + GoSlice b = {buff1, 0, 257}; + randBytes(&b, 256); + SKY_cipher_HashRipemd160(b, &r2); + ck_assert_int_eq(isU8Eq(tmp, r2, sizeof(cipher__Ripemd160)), 0); + freshSumRipemd160(b, &tmp); + ck_assert(isU8Eq(tmp, r2, sizeof(cipher__Ripemd160))); +} +END_TEST + +START_TEST(TestSHA256KnownValue) +{ + printf("Load TestSHA256KnownValue\n"); + typedef struct + { + char* input; + char* output; + } tmpstruct; + + tmpstruct vals[3]; + + vals[0].input = "skycoin"; + vals[0].output = + "5a42c0643bdb465d90bf673b99c14f5fa02db71513249d904573d2b8b63d353d"; + + vals[1].input = "hello world"; + vals[1].output = + "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; + + vals[2].input = "hello world asd awd awd awdapodawpokawpod "; + vals[2].output = + "99d71f95cafe05ea2dddebc35b6083bd5af0e44850c9dc5139b4476c99950be4"; + int i; + for (i = 0; i < 3; ++i) { + GoSlice slice_input; + GoSlice slice_output; + + slice_input.data = vals[i].input; + slice_input.len = strlen(vals[i].input); + slice_input.cap = strlen(vals[i].input) + 1; + + cipher__SHA256 sha; + + SKY_cipher_SumSHA256(slice_input, &sha); + + GoString_ tmp_output; + + SKY_cipher_SHA256_Hex(&sha, &tmp_output); + registerMemCleanup((void*)tmp_output.p); + + ck_assert(strncmp(tmp_output.p, vals[i].output, strlen(vals[i].output)) == SKY_OK); + } +} +END_TEST + + +START_TEST(TestSHA256Set) +{ + printf("Load TestSHA256Hex \n"); + cipher__SHA256 h; + unsigned char buff[101]; + GoSlice slice = {buff, 0, 101}; + int error; + + randBytes(&slice, 33); + error = SKY_cipher_SHA256_Set(&h, slice); + ck_assert(error == SKY_ErrInvalidLengthSHA256); + + randBytes(&slice, 100); + error = SKY_cipher_SHA256_Set(&h, slice); + ck_assert(error == SKY_ErrInvalidLengthSHA256); + + randBytes(&slice, 31); + error = SKY_cipher_SHA256_Set(&h, slice); + ck_assert(error == SKY_ErrInvalidLengthSHA256); + + randBytes(&slice, 0); + error = SKY_cipher_SHA256_Set(&h, slice); + ck_assert(error == SKY_ErrInvalidLengthSHA256); + + randBytes(&slice, 32); + error = SKY_cipher_SHA256_Set(&h, slice); + ck_assert(error == SKY_OK); + ck_assert(isU8Eq(h, slice.data, 32)); +} +END_TEST + +START_TEST(TestSHA256FromHex) +{ + printf("Load TestSHA256FromHex \n"); + unsigned int error; + cipher__SHA256 tmp; + // Invalid hex hash + GoString tmp_string = {"cawcd", 5}; + error = SKY_cipher_SHA256FromHex(tmp_string, &tmp); + ck_assert(error == SKY_ERROR); + // Truncated hex hash + cipher__SHA256 h; + unsigned char buff[130]; + char sbuff[300]; + GoSlice slice = {buff, 0, 130}; + randBytes(&slice, 128); + SKY_cipher_SumSHA256(slice, &h); + bytesnhex(h, sbuff, sizeof(h) >> 1); + GoString s1 = {sbuff, strlen(sbuff)}; + error = SKY_cipher_SHA256FromHex(s1, &h); + ck_assert(error == SKY_ErrInvalidHexLength); + + // Valid hex hash + GoString_ s2; + SKY_cipher_SHA256_Hex(&h, &s2); + cipher__SHA256 h2; + GoString tmps2 = {s2.p, s2.n}; + error = SKY_cipher_SHA256FromHex(tmps2, &h2); + ck_assert(error == SKY_OK); + ck_assert(isU8Eq(h, h2, 32)); +} +END_TEST + +START_TEST(TestSHA256Null) +{ + printf("Load TestSHA256Null \n"); + cipher__SHA256 x; + memset(&x, 0, sizeof(cipher__SHA256)); + GoUint32 result; + GoUint8 isNull; + ck_assert(SKY_cipher_SHA256_Null(&x, &isNull) == SKY_OK); + ck_assert(isNull); + char buff[130]; + GoSlice b = {buff, 0, 129}; + randBytes(&b, 128); + ck_assert(SKY_cipher_SumSHA256(b, &x) == SKY_OK); + ck_assert(SKY_cipher_SHA256_Null(&x, &isNull) == SKY_OK); + ck_assert(isNull == 0); +} +END_TEST + +// define test suite and cases +Suite* common_check_cipher_hash(void) +{ + Suite* s = suite_create("Load common check_cipher.hash"); + TCase* tc; + + tc = tcase_create("check_cipher.hash.common"); + tcase_add_test(tc, TestSHA256Set); + tcase_add_test(tc, TestAddSHA256); + tcase_add_test(tc, TestHashRipemd160); + tcase_add_test(tc, TestSHA256KnownValue); + tcase_add_test(tc, TestSHA256FromHex); + tcase_add_test(tc, TestSHA256Null); + suite_add_tcase(s, tc); + tcase_set_timeout(tc, 150); + + return s; +} diff --git a/lib/cgo/tests/check_cipher.secp256k1.c b/lib/cgo/tests/check_cipher.secp256k1.c index d7a4b56c4..258b191e9 100644 --- a/lib/cgo/tests/check_cipher.secp256k1.c +++ b/lib/cgo/tests/check_cipher.secp256k1.c @@ -18,13 +18,13 @@ START_TEST(Test_Abnormal_Keys2) { for (size_t i = 0; i < 4; i++) { GoUint8_ buffer_seckey[1024]; - coin__UxArray seckey1 = {buffer_seckey, 0, 1024}; + GoSlice_ seckey1 = {buffer_seckey, 0, 1024}; GoUint32_ err; err = SKY_base58_String2Hex(_testSeckey[i], &seckey1); ck_assert_msg(err == SKY_OK, "Fail in iteration %d, err %x != %x", i, err, SKY_OK); GoUint8_ buffer_pubkey[1024]; GoSlice seckey_slice = {seckey1.data, seckey1.len, seckey1.cap}; - coin__UxArray pubkey1 = {buffer_pubkey, 0, 1024}; + GoSlice_ pubkey1 = {buffer_pubkey, 0, 1024}; err = SKY_secp256k1_PubkeyFromSeckey(seckey_slice, &pubkey1); ck_assert_msg(err == SKY_OK, "Fail in iteration %d, err %x != %x", i, err, SKY_OK); GoSlice pubkey_slice = {pubkey1.data, pubkey1.len, pubkey1.cap}; @@ -38,32 +38,32 @@ START_TEST(Test_Abnormal_Keys3) { for (size_t i = 0; i < 4; i++) { GoUint8_ buffer_seckey[1024]; - coin__UxArray seckey1 = {buffer_seckey, 0, 1024}; + GoSlice_ seckey1 = {buffer_seckey, 0, 1024}; GoUint32 err; err = SKY_base58_String2Hex(_testSeckey[i], &seckey1); ck_assert_msg(err == SKY_OK, "Fail in iteration %d, err %x != %x", i, err, SKY_OK); GoUint8_ buffer_pubkey[1024]; GoSlice seckey_slice = {seckey1.data, seckey1.len, seckey1.cap}; - coin__UxArray pubkey1 = {buffer_pubkey, 0, 1024}; + GoSlice_ pubkey1 = {buffer_pubkey, 0, 1024}; err = SKY_secp256k1_PubkeyFromSeckey(seckey_slice, &pubkey1); ck_assert_msg(err == SKY_OK, "Fail in iteration %d, err %x != %x", i, err, SKY_OK); GoSlice pubkey1_slice = {pubkey1.data, pubkey1.len, pubkey1.cap}; GoInt n = rand() % 4; GoUint8_ buffer_seckey2[1024]; - coin__UxArray seckey2 = {buffer_seckey, 0, 1024}; + GoSlice_ seckey2 = {buffer_seckey, 0, 1024}; err = SKY_base58_String2Hex(_testSeckey[n], &seckey2); ck_assert_msg(err == SKY_OK, "Fail in iteration %d, err %x != %x", i, err, SKY_OK); GoUint8_ buffer_pubkey2[1024]; GoSlice seckey2_slice = {seckey2.data, seckey2.len, seckey2.cap}; - coin__UxArray pubkey2 = {buffer_pubkey2, 0, 1024}; + GoSlice_ pubkey2 = {buffer_pubkey2, 0, 1024}; err = SKY_secp256k1_PubkeyFromSeckey(seckey2_slice, &pubkey2); ck_assert_msg(err == SKY_OK, "Fail in iteration %d, err %x != %x", i, err, SKY_OK); GoSlice pubkey2_slice = {pubkey2.data, pubkey2.len, pubkey2.cap}; GoUint8 buffer_puba[1024]; - coin__UxArray puba = {buffer_puba, 0, 1024}; + GoSlice_ puba = {buffer_puba, 0, 1024}; GoUint8 buffer_pubb[1024]; - coin__UxArray pubb = {buffer_pubb, 0, 1024}; + GoSlice_ pubb = {buffer_pubb, 0, 1024}; err = SKY_secp256k1_ECDH(pubkey1_slice, seckey2_slice, &puba); ck_assert_msg(err == SKY_OK, "Fail in iteration %d, err %x != %x", i, err, SKY_OK); err = SKY_secp256k1_ECDH(pubkey2_slice, seckey_slice, &pubb); diff --git a/lib/cgo/tests/check_cipher.testsuite.c b/lib/cgo/tests/check_cipher.testsuite.c index 532e43351..1e69e77ee 100644 --- a/lib/cgo/tests/check_cipher.testsuite.c +++ b/lib/cgo/tests/check_cipher.testsuite.c @@ -94,7 +94,7 @@ Suite* cipher_testsuite(void) tc = tcase_create("cipher.testsuite"); tcase_add_checked_fixture(tc, setup, teardown); - tcase_add_test(tc, TestManyAddresses); + // tcase_add_test(tc, TestManyAddresses); suite_add_tcase(s, tc); tcase_set_timeout(tc, 150); diff --git a/lib/cgo/tests/check_coin.outputs.c b/lib/cgo/tests/check_coin.outputs.c index 2c5af1f54..f90a5329e 100644 --- a/lib/cgo/tests/check_coin.outputs.c +++ b/lib/cgo/tests/check_coin.outputs.c @@ -324,14 +324,14 @@ START_TEST(TestUxArraySub) ck_assert_msg(result == SKY_OK, "makeUxArray failed"); int elems_size = sizeof(coin__UxOut); - cutSlice(&uxa, 0, 1, elems_size, &t1); - ck_assert_msg(result == SKY_OK, "cutSlice failed"); - result = concatSlices(&t1, &uxb, elems_size, &t2); - ck_assert_msg(result == SKY_OK, "concatSlices failed"); - result = cutSlice(&uxa, 1, 2, elems_size, &t3); - ck_assert_msg(result == SKY_OK, "cutSlice failed"); - result = concatSlices(&t2, &t3, elems_size, &uxc); - ck_assert_msg(result == SKY_OK, "concatSlices failed"); + cutUxArray(&uxa, 0, 1, elems_size, &t1); + ck_assert_msg(result == SKY_OK, "cutUxArray failed"); + result = concatUxArray(&t1, &uxb, elems_size, &t2); + ck_assert_msg(result == SKY_OK, "concatUxArray failed"); + result = cutUxArray(&uxa, 1, 2, elems_size, &t3); + ck_assert_msg(result == SKY_OK, "cutUxArray failed"); + result = concatUxArray(&t2, &t3, elems_size, &uxc); + ck_assert_msg(result == SKY_OK, "concatUxArray failed"); // //TODO: Fix comparision memset(&uxd, 0, arraySize); result = SKY_coin_UxArray_Sub(&uxc, &uxa, &uxd); @@ -342,7 +342,7 @@ START_TEST(TestUxArraySub) result = SKY_coin_UxArray_Sub(&uxc, &uxb, &uxd); ck_assert_msg(result == SKY_OK, "SKY_coin_UxArray_Sub failed"); ck_assert_msg(uxd.len == 2, "uxd length must be 2 and it is: %s", uxd.len); - cutSlice(&uxa, 0, 2, elems_size, &t1); + cutUxArray(&uxa, 0, 2, elems_size, &t1); ck_assert(isUxArrayEq(&uxd, &t1)); // No intersection diff --git a/lib/cgo/tests/check_coin.transactions.c b/lib/cgo/tests/check_coin.transactions.c index 2383a5edb..075d6fe4b 100644 --- a/lib/cgo/tests/check_coin.transactions.c +++ b/lib/cgo/tests/check_coin.transactions.c @@ -16,21 +16,21 @@ GoUint64 Million = 1000000; START_TEST(TestTransactionVerify) { printf("Load TestTransactionVerify\n"); - unsigned long long MaxUint64 = - 0xFFFFFFFFFFFFFFFF; - unsigned int MaxUint16 = 0xFFFF; - int result; + GoUint64 MaxUint64 = 0xFFFFFFFFFFFFFFFF; + GoUint32 MaxUint16 = 0xFFFF; + GoUint32 result; - coin__Transaction* ptx; - Transaction__Handle handle; + Transaction__Handle handle = 0; // Mismatch header hash - ptx = makeTransaction(&handle); - memset(ptx->InnerHash, 0, sizeof(cipher__SHA256)); + makeTransaction(&handle); + cipher__SHA256 nullsha = ""; + result = SKY_coin_Transaction_SetInnerHash(&handle, &nullsha); + ck_assert(result == SKY_OK); result = SKY_coin_Transaction_Verify(handle); ck_assert(result == SKY_ERROR); // No inputs - ptx = makeTransaction(&handle); + makeTransaction(&handle); result = SKY_coin_Transaction_ResetInputs(handle, 0); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); @@ -39,7 +39,7 @@ START_TEST(TestTransactionVerify) ck_assert(result == SKY_ERROR); // No outputs - ptx = makeTransaction(&handle); + makeTransaction(&handle); result = SKY_coin_Transaction_ResetOutputs(handle, 0); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); @@ -48,7 +48,7 @@ START_TEST(TestTransactionVerify) ck_assert(result == SKY_ERROR); // Invalid number of Sigs - ptx = makeTransaction(&handle); + makeTransaction(&handle); result = SKY_coin_Transaction_ResetSignatures(handle, 0); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); @@ -63,7 +63,7 @@ START_TEST(TestTransactionVerify) ck_assert(result == SKY_ERROR); // Too many sigs & inputs - ptx = makeTransaction(&handle); + makeTransaction(&handle); result = SKY_coin_Transaction_ResetSignatures(handle, MaxUint16); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_ResetInputs(handle, MaxUint16); @@ -80,8 +80,9 @@ START_TEST(TestTransactionVerify) memset(&seckey, 0, sizeof(cipher__SecKey)); cipher__SHA256 sha256; makeUxOutWithSecret(&ux, &seckey); - ptx = makeTransactionFromUxOut(&ux, &seckey, &handle); - memcpy(&sha256, ptx->In.data, sizeof(cipher__SHA256)); + makeTransactionFromUxOut(&ux, &seckey, &handle); + result = SKY_coin_Transaction_SetInputAt(handle, 0, &sha256); + ck_assert(result == SKY_OK); GoUint16 r; result = SKY_coin_Transaction_PushInput(handle, &sha256); result = SKY_coin_Transaction_ResetSignatures(handle, 0); @@ -104,37 +105,48 @@ START_TEST(TestTransactionVerify) #endif // Duplicate outputs - ptx = makeTransaction(&handle); - coin__TransactionOutput* pOutput = ptx->Out.data; + makeTransaction(&handle); + GoInt8 bufferSiceOut[1024]; + coin__TransactionOutput pOutput; + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); + cipher__Address addr; - memcpy(&addr, &pOutput->Address, sizeof(cipher__Address)); - result = SKY_coin_Transaction_PushOutput(handle, &addr, pOutput->Coins, - pOutput->Hours); + memcpy(&addr, &pOutput.Address, sizeof(cipher__Address)); + result = SKY_coin_Transaction_PushOutput(handle, &addr, pOutput.Coins, pOutput.Hours); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_Verify(handle); - ck_assert(result == SKY_ERROR); + ck_assert_int_eq(result, SKY_ERROR); // Invalid signature, empty - ptx = makeTransaction(&handle); - memset(ptx->Sigs.data, 0, sizeof(cipher__Sig)); + makeTransaction(&handle); + cipher__Sig nullsig = ""; + result = SKY_coin_Transaction_SetSignatureAt(handle, 0, &nullsig); + ck_assert_int_eq(result, SKY_OK); result = SKY_coin_Transaction_Verify(handle); ck_assert_int_eq(result, SKY_ERROR); // Output coins are 0 - ptx = makeTransaction(&handle); - pOutput = ptx->Out.data; - pOutput->Coins = 0; + makeTransaction(&handle); + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); + pOutput.Coins = 0; + result = SKY_coin_Transaction_SetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_Verify(handle); ck_assert(result == SKY_ERROR); // Output coin overflow - ptx = makeTransaction(&handle); - pOutput = ptx->Out.data; - pOutput->Coins = MaxUint64 - 3000000; + makeTransaction(&handle); + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); + pOutput.Coins = MaxUint64 - 3000000; + result = SKY_coin_Transaction_SetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_Verify(handle); @@ -142,9 +154,12 @@ START_TEST(TestTransactionVerify) // Output coins are not multiples of 1e6 (valid, decimal restriction is not // enforced here) - ptx = makeTransaction(&handle); - pOutput = ptx->Out.data; - pOutput->Coins += 10; + makeTransaction(&handle); + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); + pOutput.Coins += 10; + result = SKY_coin_Transaction_SetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_ResetSignatures(handle, 0); @@ -157,16 +172,22 @@ START_TEST(TestTransactionVerify) seckeys.cap = 1; result = SKY_coin_Transaction_SignInputs(handle, seckeys); ck_assert(result == SKY_OK); - ck_assert(pOutput->Coins % 1000000 != 0); + ck_assert(pOutput.Coins % 1000000 != 0); result = SKY_coin_Transaction_Verify(handle); ck_assert(result == SKY_OK); // Valid - ptx = makeTransaction(&handle); - pOutput = ptx->Out.data; - pOutput->Coins = 10000000; - pOutput++; - pOutput->Coins = 1000000; + makeTransaction(&handle); + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); + pOutput.Coins = 10000000; + result = SKY_coin_Transaction_SetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); + result = SKY_coin_Transaction_GetOutputAt(handle, 1, &pOutput); + ck_assert(result == SKY_OK); + pOutput.Coins = 1000000; + result = SKY_coin_Transaction_SetOutputAt(handle, 1, &pOutput); + ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_Verify(handle); @@ -177,31 +198,32 @@ END_TEST START_TEST(TestTransactionPushInput) { printf("Load TestTransactionPushInput\n"); - unsigned long long MaxUint64 = 0xFFFFFFFFFFFFFFFF; - unsigned int MaxUint16 = 0xFFFF; - int result; + GoUint64 MaxUint64 = 0xFFFFFFFFFFFFFFFF; + GoUint32 MaxUint16 = 0xFFFF; + GoUint32 result; Transaction__Handle handle; - coin__Transaction* ptx; coin__UxOut ux; - ptx = makeEmptyTransaction(&handle); + makeEmptyTransaction(&handle); makeUxOut(&ux); cipher__SHA256 hash; result = SKY_coin_UxOut_Hash(&ux, &hash); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_PushInput(handle, &hash); ck_assert(result == SKY_OK); - ck_assert_msg(ptx->In.len == 1, "Fail len is %d", ptx->In.len); - cipher__SHA256* pIn = ptx->In.data; + GoSlice_* SliceIn = NULL; + result = SKY_coin_Transaction_GetIn(handle, SliceIn); + ck_assert_msg(SliceIn->len == 1, "Fail len is %d", SliceIn->len); + cipher__SHA256* pIn = SliceIn->data; ck_assert(isU8Eq(hash, *pIn, sizeof(cipher__SHA256))); - int len = ptx->In.len; + int len = SliceIn->len; void* data = malloc(len * sizeof(cipher__SHA256)); ck_assert(data != NULL); registerMemCleanup(data); - memcpy(data, ptx->In.data, len * sizeof(cipher__SHA256)); + memcpy(data, SliceIn->data, len * sizeof(cipher__SHA256)); result = SKY_coin_Transaction_ResetInputs(handle, MaxUint16 + len); ck_assert(result == SKY_OK); - memcpy(ptx->In.data, data, len * sizeof(cipher__Sig)); + memcpy(SliceIn->data, data, len * sizeof(cipher__Sig)); freeRegisteredMemCleanup(data); makeUxOut(&ux); result = SKY_coin_UxOut_Hash(&ux, &hash); @@ -216,31 +238,36 @@ START_TEST(TestTransactionPushOutput) printf("Load TestTransactionPushOutput\n"); GoUint32 result; Transaction__Handle handle; - coin__Transaction* ptx; - ptx = makeEmptyTransaction(&handle); + makeEmptyTransaction(&handle); cipher__Address addr; makeAddress(&addr); result = SKY_coin_Transaction_PushOutput(handle, &addr, 100, 150); ck_assert(result == SKY_OK); - ck_assert(ptx->Out.len == 1); - coin__TransactionOutput* pOutput = ptx->Out.data; + GoInt lenght; + result = SKY_coin_Transaction_GetOutputsCount(handle, &lenght); + ck_assert(result == SKY_OK); + ck_assert(lenght == 1); + coin__TransactionOutput pOutput; + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); + ck_assert(result == SKY_OK); coin__TransactionOutput output; memcpy(&output.Address, &addr, sizeof(cipher__Address)); output.Coins = 100; output.Hours = 150; - ck_assert(isTransactionOutputEq(&output, pOutput)); + ck_assert(isTransactionOutputEq(&output, &pOutput)); for (int i = 1; i < 20; i++) { makeAddress(&addr); result = SKY_coin_Transaction_PushOutput(handle, &addr, i * 100, i * 50); ck_assert(result == SKY_OK); - ck_assert(ptx->Out.len == i + 1); - pOutput = ptx->Out.data; - pOutput += i; + result = SKY_coin_Transaction_GetOutputsCount(handle, &lenght); + ck_assert_int_eq(lenght, i + 1); + result = SKY_coin_Transaction_GetOutputAt(handle, i, &pOutput); + ck_assert(result == SKY_OK); memcpy(&output.Address, &addr, sizeof(cipher__Address)); output.Coins = i * 100; output.Hours = i * 50; - ck_assert(isTransactionOutputEq(&output, pOutput)); + ck_assert(isTransactionOutputEq(&output, &pOutput)); } } END_TEST @@ -250,8 +277,7 @@ START_TEST(TestTransactionHash) printf("Load TestTransactionHash\n"); GoUint32 result; Transaction__Handle handle; - coin__Transaction* ptx; - ptx = makeEmptyTransaction(&handle); + makeEmptyTransaction(&handle); cipher__SHA256 nullHash, hash1, hash2; memset(&nullHash, 0, sizeof(cipher__SHA256)); @@ -269,19 +295,19 @@ START_TEST(TestTransactionUpdateHeader) printf("Load TestTransactionUpdateHeader\n"); GoUint32 result; Transaction__Handle handle; - coin__Transaction* ptx; - ptx = makeTransaction(&handle); + makeTransaction(&handle); cipher__SHA256 hash; cipher__SHA256 nullHash = ""; cipher__SHA256 hashInner; - memcpy(&hash, &ptx->InnerHash, sizeof(cipher__SHA256)); - memset(&ptx->InnerHash, 0, sizeof(cipher__SHA256)); + result = SKY_coin_Transaction_GetInnerHash(handle, &hash); + ck_assert(result == SKY_OK); + result = SKY_coin_Transaction_SetInnerHash(&handle, &nullHash); + ck_assert(result == SKY_OK); result = SKY_coin_Transaction_UpdateHeader(handle); - ck_assert_int_eq(isU8Eq(ptx->InnerHash, nullHash, sizeof(cipher__SHA256)), 0); - ck_assert_int_eq(isU8Eq(ptx->InnerHash, hash, sizeof(cipher__SHA256)), 1); + ck_assert_int_eq(isU8Eq(hash, nullHash, sizeof(cipher__SHA256)), 0); result = SKY_coin_Transaction_HashInner(handle, &hashInner); ck_assert(result == SKY_OK); - ck_assert(isU8Eq(hashInner, ptx->InnerHash, sizeof(cipher__SHA256))); + ck_assert(isU8Eq(hashInner, hash, sizeof(cipher__SHA256))); } END_TEST @@ -298,7 +324,7 @@ START_TEST(TestTransactionsSize) result = SKY_coin_Transactions_GetAt(txns, i, &handle); registerHandleClose(handle); ck_assert(result == SKY_OK); - coin__UxArray p1 = {NULL, 0, 0}; + GoSlice_ p1 = {NULL, 0, 0}; result = SKY_coin_Transaction_Serialize(handle, &p1); ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_Serialize"); size += p1.len; @@ -316,8 +342,7 @@ START_TEST(TestTransactionVerifyInput) printf("Load TestTransactionVerifyInput\n"); GoUint32 result; Transaction__Handle handle; - coin__Transaction* ptx; - ptx = makeTransaction(&handle); + makeTransaction(&handle); coin__UxArray ux; memset(&ux, 0, sizeof(coin__UxArray)); result = SKY_coin_VerifyInputSignatures(handle, &ux); @@ -339,7 +364,7 @@ START_TEST(TestTransactionVerifyInput) result = makeUxOutWithSecret(&uxOut, &seckey); ck_assert(result == SKY_OK); - ptx = makeTransactionFromUxOut(&uxOut, &seckey, &handle); + makeTransactionFromUxOut(&uxOut, &seckey, &handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_ResetSignatures(handle, 0); ck_assert(result == SKY_OK); @@ -352,11 +377,12 @@ START_TEST(TestTransactionVerifyInput) memset(&sig, 0, sizeof(cipher__Sig)); result = makeUxOutWithSecret(&uxOut, &seckey); ck_assert(result == SKY_OK); - ptx = makeTransactionFromUxOut(&uxOut, &seckey, &handle); + makeTransactionFromUxOut(&uxOut, &seckey, &handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_ResetSignatures(handle, 1); ck_assert(result == SKY_OK); - memcpy(ptx->Sigs.data, &sig, sizeof(cipher__Sig)); + SKY_coin_Transaction_GetSignatureAt(handle, 0, &sig); + ck_assert(result == SKY_OK); ux.data = &uxOut; ux.len = 1; ux.cap = 1; @@ -366,9 +392,10 @@ START_TEST(TestTransactionVerifyInput) // Invalid Tx Inner Hash result = makeUxOutWithSecret(&uxOut, &seckey); ck_assert(result == SKY_OK); - ptx = makeTransactionFromUxOut(&uxOut, &seckey, &handle); + makeTransactionFromUxOut(&uxOut, &seckey, &handle); ck_assert(result == SKY_OK); - memset(ptx->InnerHash, 0, sizeof(cipher__SHA256)); + cipher__SHA256 sha_null; + SKY_coin_Transaction_SetInnerHash(&handle, &sha_null); ux.data = &uxOut; ux.len = 1; ux.cap = 1; @@ -378,7 +405,7 @@ START_TEST(TestTransactionVerifyInput) // Ux hash mismatch result = makeUxOutWithSecret(&uxOut, &seckey); ck_assert(result == SKY_OK); - ptx = makeTransactionFromUxOut(&uxOut, &seckey, &handle); + makeTransactionFromUxOut(&uxOut, &seckey, &handle); ck_assert(result == SKY_OK); memset(&uxOut, 0, sizeof(coin__UxOut)); ux.data = &uxOut; @@ -390,11 +417,13 @@ START_TEST(TestTransactionVerifyInput) // Invalid signature result = makeUxOutWithSecret(&uxOut, &seckey); ck_assert(result == SKY_OK); - ptx = makeTransactionFromUxOut(&uxOut, &seckey, &handle); + makeTransactionFromUxOut(&uxOut, &seckey, &handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_ResetSignatures(handle, 1); ck_assert(result == SKY_OK); - memset(ptx->Sigs.data, 0, sizeof(cipher__Sig)); + cipher__Sig sig_null; + result = SKY_coin_Transaction_SetSignatureAt(handle, 0, &sig_null); + ck_assert(result == SKY_OK); ux.data = &uxOut; ux.len = 1; ux.cap = 1; @@ -404,7 +433,7 @@ START_TEST(TestTransactionVerifyInput) // Valid result = makeUxOutWithSecret(&uxOut, &seckey); ck_assert(result == SKY_OK); - ptx = makeTransactionFromUxOut(&uxOut, &seckey, &handle); + makeTransactionFromUxOut(&uxOut, &seckey, &handle); ck_assert(result == SKY_OK); ux.data = &uxOut; ux.len = 1; @@ -418,7 +447,6 @@ START_TEST(TestTransactionSignInputs) { printf("Load TestTransactionSignInputs\n"); GoUint32 result; - coin__Transaction* ptx; Transaction__Handle handle; coin__UxOut ux, ux2; cipher__SecKey seckey, seckey2; @@ -429,7 +457,7 @@ START_TEST(TestTransactionSignInputs) GoSlice keys; // Error if txns already signed - ptx = makeEmptyTransaction(&handle); + makeEmptyTransaction(&handle); result = SKY_coin_Transaction_ResetSignatures(handle, 1); ck_assert(result == SKY_OK); @@ -441,7 +469,7 @@ START_TEST(TestTransactionSignInputs) ck_assert(result == SKY_ERROR); // Panics if not enough keys - ptx = makeEmptyTransaction(&handle); + makeEmptyTransaction(&handle); memset(&seckey, 0, sizeof(cipher__SecKey)); memset(&seckey2, 0, sizeof(cipher__SecKey)); result = makeUxOutWithSecret(&ux, &seckey); @@ -459,13 +487,17 @@ START_TEST(TestTransactionSignInputs) makeAddress(&addr); result = SKY_coin_Transaction_PushOutput(handle, &addr, 40, 80); ck_assert(result == SKY_OK); - ck_assert(ptx->Sigs.len == 0); + GoInt SigLen; + SKY_coin_Transaction_GetSignaturesCount(handle, &SigLen); + ck_assert(SigLen == 0); keys.data = &seckey; keys.len = 1; keys.cap = 1; result = SKY_coin_Transaction_SignInputs(handle, keys); ck_assert(result == SKY_ERROR); - ck_assert(ptx->Sigs.len == 0); + SKY_coin_Transaction_GetSignaturesCount(handle, &SigLen); + ck_assert(SigLen == 0); + ck_assert(SigLen == 0); // Valid signing result = SKY_coin_Transaction_HashInner(handle, &hash); @@ -478,7 +510,8 @@ START_TEST(TestTransactionSignInputs) memcpy(((cipher__SecKey*)keys.data) + 1, &seckey2, sizeof(cipher__SecKey)); result = SKY_coin_Transaction_SignInputs(handle, keys); ck_assert(result == SKY_OK); - ck_assert(ptx->Sigs.len == 2); + SKY_coin_Transaction_GetSignaturesCount(handle, &SigLen); + ck_assert(SigLen == 2); result = SKY_coin_Transaction_HashInner(handle, &hash2); ck_assert(result == SKY_OK); ck_assert(isU8Eq(hash2, hash, sizeof(cipher__SHA256)) == 0); @@ -493,23 +526,22 @@ START_TEST(TestTransactionSignInputs) ck_assert(result == SKY_OK); cipher__SHA256 addHash, addHash2; - result = - SKY_cipher_AddSHA256(&hash, (cipher__SHA256*)ptx->In.data, &addHash); + cipher__SHA256 hash_tmp; + SKY_coin_Transaction_GetInputAt(handle, 0, &hash_tmp); + result = SKY_cipher_AddSHA256(&hash, &hash_tmp, &addHash); ck_assert(result == SKY_OK); - result = SKY_cipher_AddSHA256(&hash, ((cipher__SHA256*)ptx->In.data) + 1, - &addHash2); + SKY_coin_Transaction_GetInputAt(handle, 1, &hash_tmp); + result = SKY_cipher_AddSHA256(&hash, &hash_tmp, &addHash2); ck_assert(result == SKY_OK); - result = SKY_cipher_VerifyAddressSignedHash( - &addr, (cipher__Sig*)ptx->Sigs.data, &addHash); + cipher__Sig sig; + SKY_coin_Transaction_GetSignatureAt(handle, 0, &sig); + result = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &addHash); ck_assert(result == SKY_OK); - result = SKY_cipher_VerifyAddressSignedHash( - &addr2, ((cipher__Sig*)ptx->Sigs.data) + 1, &addHash2); + SKY_coin_Transaction_GetSignatureAt(handle, 1, &sig); + result = SKY_cipher_VerifyAddressSignedHash(&addr2, &sig, &addHash2); ck_assert(result == SKY_OK); - result = SKY_cipher_VerifyAddressSignedHash( - &addr, ((cipher__Sig*)ptx->Sigs.data) + 1, &hash); - ck_assert(result == SKY_ERROR); - result = SKY_cipher_VerifyAddressSignedHash( - &addr2, (cipher__Sig*)ptx->Sigs.data, &hash); + SKY_coin_Transaction_GetSignatureAt(handle, 2, &sig); + result = SKY_cipher_VerifyAddressSignedHash(&addr, &sig, &hash); ck_assert(result == SKY_ERROR); } END_TEST @@ -517,70 +549,65 @@ END_TEST START_TEST(TestTransactionHashInner) { printf("Load TestTransactionHashInner\n"); - GoUint32 result; - Transaction__Handle handle1 = 0, handle2 = 0; - coin__Transaction* ptx = NULL; - coin__Transaction* ptx2 = NULL; - ptx = makeTransaction(&handle1); - cipher__SHA256 hash, nullHash = ""; - result = SKY_coin_Transaction_HashInner(handle1, &hash); - ck_assert(result == SKY_OK); - ck_assert_int_eq(isU8Eq(nullHash, hash, sizeof(cipher__SHA256)), 0); - - // If tx.In is changed, hash should change - ptx2 = copyTransaction(handle1, &handle2); - ck_assert_mem_ne(ptx, ptx2, sizeof(coin__Transaction)); - ck_assert(ptx2->In.len > 0); - coin__UxOut uxOut; - makeUxOut(&uxOut); - cipher__SHA256* pHash = ptx2->In.data; - result = SKY_coin_UxOut_Hash(&uxOut, pHash); - ck_assert(result == SKY_OK); - ck_assert_mem_ne(ptx, ptx2, sizeof(coin__Transaction)); - cipher__SHA256 hash1, hash2; - result = SKY_coin_Transaction_HashInner(handle1, &hash1); - ck_assert(result == SKY_OK); - result = SKY_coin_Transaction_HashInner(handle2, &hash2); - ck_assert(result == SKY_OK); - ck_assert_int_eq(isU8Eq(hash1, hash2, sizeof(cipher__SHA256)), 0); - - // If tx.Out is changed, hash should change - handle2 = 0; - ptx2 = copyTransaction(handle1, &handle2); - ck_assert(ptx != ptx2); - ck_assert_mem_ne(ptx, ptx2, sizeof(coin__Transaction)); - coin__TransactionOutput* output = ptx2->Out.data; - cipher__Address addr; - memset(&addr, 0, sizeof(cipher__Address)); - makeAddress(&addr); - registerMemCleanup(&addr); - memcpy(&output->Address, &addr, sizeof(cipher__Address)); + Transaction__Handle txn = 0; + Transaction__Handle txn2 = 0; + makeTransaction(&txn); - ck_assert_mem_ne(ptx, ptx2, sizeof(coin__Transaction)); - ck_assert(isAddressEq(&addr, &output->Address)); - result = SKY_coin_Transaction_HashInner(handle1, &hash1); - ck_assert(result == SKY_OK); - result = SKY_coin_Transaction_HashInner(handle2, &hash2); - ck_assert(result == SKY_OK); - ck_assert_int_eq(isU8Eq(hash1, hash2, sizeof(cipher__SHA256)), 0); - - // If tx.Head is changed, hash should not change - ptx2 = copyTransaction(handle1, &handle2); - int len = ptx2->Sigs.len; - cipher__Sig* newSigs = malloc((len + 1) * sizeof(cipher__Sig)); - ck_assert(newSigs != NULL); - registerMemCleanup(newSigs); - memcpy(newSigs, ptx2->Sigs.data, len * sizeof(cipher__Sig)); - result = SKY_coin_Transaction_ResetSignatures(handle2, len + 1); - ck_assert(result == SKY_OK); - memcpy(ptx2->Sigs.data, newSigs, len * sizeof(cipher__Sig)); - newSigs += len; - memset(newSigs, 0, sizeof(cipher__Sig)); - result = SKY_coin_Transaction_HashInner(handle1, &hash1); - ck_assert(result == SKY_OK); - result = SKY_coin_Transaction_HashInner(handle2, &hash2); - ck_assert(result == SKY_OK); - ck_assert(isU8Eq(hash1, hash2, sizeof(cipher__SHA256))); + // If txn.In is changed, inner hash should change + copyTransaction(txn, &txn2); + coin__UxOut ux; + GoUint32 err = makeUxOut(&ux); + cipher__SHA256 sha_tmp; + err = SKY_coin_UxOut_Hash(&ux, &sha_tmp); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_SetInputAt(txn2, 0, &sha_tmp); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isTransactionHandleEq(&txn, &txn2) == 0); + err = SKY_coin_UxOut_Hash(&ux, &sha_tmp); + ck_assert_int_eq(err, SKY_OK); + cipher__SHA256 sha_tmp2; + err = SKY_coin_Transaction_GetInputAt(txn2, 0, &sha_tmp2); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isSHA256Eq(&sha_tmp2, &sha_tmp)); + err = SKY_coin_Transaction_HashInner(txn, &sha_tmp); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_HashInner(txn2, &sha_tmp2); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isSHA256Eq(&sha_tmp2, &sha_tmp) == 0); + + // If txn.Out is changed, inner hash should change + copyTransaction(txn, &txn2); + cipher__Address a; + makeAddress(&a); + coin__TransactionOutput out_tmp; + err = SKY_coin_Transaction_GetOutputAt(txn2, 0, &out_tmp); + ck_assert_int_eq(err, SKY_OK); + out_tmp.Address = a; + err = SKY_coin_Transaction_SetOutputAt(txn2, 0, &out_tmp); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isTransactionHandleEq(&txn, &txn2) == 0); + err = SKY_coin_Transaction_GetOutputAt(txn2, 0, &out_tmp); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isAddressEq(&out_tmp.Address, &a)); + err = SKY_coin_Transaction_HashInner(txn, &sha_tmp); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_HashInner(txn2, &sha_tmp2); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isSHA256Eq(&sha_tmp2, &sha_tmp) == 0); + + // If txn.Head is changed, inner hash should not change + copyTransaction(txn, &txn2); + GoInt post; + SKY_coin_Transaction_GetSignaturesCount(txn, &post); + ck_assert_int_eq(err, SKY_OK); + cipher__Sig nullsig; + err = SKY_coin_Transaction_PushSignature(txn, &nullsig); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_HashInner(txn, &sha_tmp); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_HashInner(txn2, &sha_tmp2); + ck_assert_int_eq(err, SKY_OK); + ck_assert(isSHA256Eq(&sha_tmp2, &sha_tmp)); } END_TEST @@ -589,29 +616,23 @@ START_TEST(TestTransactionSerialization) printf("Load TestTransactionSerialization\n"); GoUint32 result; Transaction__Handle handle = 0; - coin__Transaction* ptx = makeTransaction(&handle); + makeTransaction(&handle); unsigned char buffer[1024]; - coin__UxArray data = {buffer, 0, 1024}; - result = SKY_coin_Transaction_Serialize(handle, &data); + GoSlice d = {buffer, 0, 1024}; + result = SKY_coin_Transaction_Serialize(handle, &d); ck_assert(result == SKY_OK); - registerMemCleanup(data.data); - coin__Transaction* ptx2 = NULL; Transaction__Handle handle2 = 0; - GoSlice d = {data.data, data.len, data.cap}; result = SKY_coin_TransactionDeserialize(d, &handle2); ck_assert(result == SKY_OK); - result = SKY_coin_GetTransactionObject(handle2, &ptx2); - ck_assert(result == SKY_OK); - ck_assert(isTransactionEq(ptx, ptx2)); + ck_assert(isTransactionHandleEq(&handle, &handle2)); } END_TEST START_TEST(TestTransactionOutputHours) { printf("Load TestTransactionOutputHours\n"); - coin__Transaction* ptx; Transaction__Handle handle; - ptx = makeEmptyTransaction(&handle); + makeEmptyTransaction(&handle); cipher__Address addr; makeAddress(&addr); int result; @@ -654,7 +675,7 @@ START_TEST(TestTransactionsHashes) cipher__SHA256* ph = hashes.data; cipher__SHA256 hash; for (int i = 0; i < 4; i++) { - Transaction__Handle handle; + Transaction__Handle handle = 0; result = SKY_coin_Transactions_GetAt(hTxns, i, &handle); ck_assert(result == SKY_OK); result = SKY_coin_Transaction_Hash(handle, &hash); @@ -946,11 +967,10 @@ END_TEST GoUint32_ feeCalculator1(Transaction__Handle handle, GoUint64_* pFee, void* context) { - coin__Transaction* pTx; - int result = SKY_coin_GetTransactionObject(handle, &pTx); + coin__TransactionOutput pOutput; + int result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); if (result == SKY_OK) { - coin__TransactionOutput* pOutput = pTx->Out.data; - *pFee = 100 * Million - pOutput->Hours; + *pFee = 100 * Million - pOutput.Hours; } return result; } @@ -965,14 +985,7 @@ void assertTransactionsHandleEqual(Transaction__Handle h1, Transaction__Handle h2, char* testName) { - coin__Transaction* pTx1 = NULL; - coin__Transaction* pTx2 = NULL; - GoUint32 result; - result = SKY_coin_GetTransactionObject(h1, &pTx1); - ck_assert(result == SKY_OK); - result = SKY_coin_GetTransactionObject(h2, &pTx2); - ck_assert(result == SKY_OK); - ck_assert_msg(isTransactionEq(pTx1, pTx2), + ck_assert_msg(isTransactionHandleEq(&h1, &h2), "Failed SortTransactions test \"%s\"", testName); } @@ -1026,14 +1039,13 @@ GoUint32_ feeCalculator3(Transaction__Handle handle, GoUint64_* pFee, void* cont unsigned long long MaxUint64 = 0xFFFFFFFFFFFFFFFF; unsigned int MaxUint16 = 0xFFFF; int result = SKY_coin_Transaction_Hash(handle, &hash); - if (result == SKY_OK && (memcmp(&hash, thirdHash, sizeof(cipher__SHA256)))) { + if (result == SKY_OK && isSHA256Eq(thirdHash, &hash)) { *pFee = MaxUint64 / 2; } else { - coin__Transaction* pTx; - result = SKY_coin_GetTransactionObject(handle, &pTx); + coin__TransactionOutput pOutput; + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); if (result == SKY_OK) { - coin__TransactionOutput* pOutput = pTx->Out.data; - *pFee = 100 * Million - pOutput->Hours; + *pFee = 100 * Million - pOutput.Hours; } } return result; @@ -1045,15 +1057,14 @@ GoUint32_ feeCalculator4(Transaction__Handle handle, GoUint64_* pFee, void* cont cipher__SHA256* thirdHash = (cipher__SHA256*)context; int result = SKY_coin_Transaction_Hash(handle, &hash); - if (result == SKY_OK && (memcmp(&hash, thirdHash, sizeof(cipher__SHA256)))) { + if (result == SKY_OK && isSHA256Eq(thirdHash, &hash)) { *pFee = 0; result = SKY_ERROR; } else { - coin__Transaction* pTx; - result = SKY_coin_GetTransactionObject(handle, &pTx); + coin__TransactionOutput pOutput; + result = SKY_coin_Transaction_GetOutputAt(handle, 0, &pOutput); if (result == SKY_OK) { - coin__TransactionOutput* pOutput = pTx->Out.data; - *pFee = 100 * Million - pOutput->Hours; + *pFee = 100 * Million - pOutput.Hours; } } return result; @@ -1064,7 +1075,6 @@ START_TEST(TestSortTransactions) int n = 6; int i; GoUint32 result; - Transactions__Handle transactionsHandle = 0; Transactions__Handle transactionsHandle2 = 0; Transactions__Handle hashSortedTxnsHandle = 0; @@ -1131,20 +1141,20 @@ Suite* coin_transaction(void) tc = tcase_create("coin.transaction"); tcase_add_checked_fixture(tc, setup, teardown); - tcase_add_test(tc, TestTransactionVerify); //ok - tcase_add_test(tc, TestTransactionPushOutput); //ok - tcase_add_test(tc, TestTransactionHash); //ok - tcase_add_test(tc, TestTransactionUpdateHeader); //ok - tcase_add_test(tc, TestTransactionsSize); //ok - tcase_add_test(tc, TestTransactionHashInner); //ok - tcase_add_test(tc, TestTransactionSerialization); //ok - tcase_add_test(tc, TestTransactionOutputHours); //ok - tcase_add_test(tc, TestTransactionsHashes); //ok - tcase_add_test(tc, TestTransactionsTruncateBytesTo); //ok - tcase_add_test(tc, TestVerifyTransactionCoinsSpending); //ok - tcase_add_test(tc, TestVerifyTransactionHoursSpending); //ok - tcase_add_test(tc, TestSortTransactions); //ok - tcase_add_test(tc, TestTransactionsFees); // ok + tcase_add_test(tc, TestTransactionVerify); + tcase_add_test(tc, TestTransactionPushOutput); + tcase_add_test(tc, TestTransactionHash); + tcase_add_test(tc, TestTransactionUpdateHeader); + tcase_add_test(tc, TestTransactionsSize); + tcase_add_test(tc, TestTransactionHashInner); + tcase_add_test(tc, TestTransactionSerialization); + tcase_add_test(tc, TestTransactionOutputHours); + tcase_add_test(tc, TestTransactionsHashes); + tcase_add_test(tc, TestTransactionsTruncateBytesTo); + tcase_add_test(tc, TestVerifyTransactionCoinsSpending); + tcase_add_test(tc, TestVerifyTransactionHoursSpending); + tcase_add_test(tc, TestSortTransactions); + tcase_add_test(tc, TestTransactionsFees); suite_add_tcase(s, tc); tcase_set_timeout(tc, INFINITY); return s; diff --git a/lib/cgo/tests/check_params.distribution.c b/lib/cgo/tests/check_params.distribution.c index 41ca0ef76..7aa2c262c 100644 --- a/lib/cgo/tests/check_params.distribution.c +++ b/lib/cgo/tests/check_params.distribution.c @@ -10,18 +10,23 @@ START_TEST(TestDistributionAddressArrays) { - coin__UxArray all = {NULL, 0, 0}; - coin__UxArray unlocked = {NULL, 0, 0}; - coin__UxArray locked = {NULL, 0, 0}; - - SKY_params_GetDistributionAddresses(&all); + GoSlice_ all = {NULL, 0, 0}; + GoSlice_ unlocked = {NULL, 0, 0}; + GoSlice_ locked = {NULL, 0, 0}; + Distribution__Handle dist = 0; + GoUint32 err = SKY_params_Distribution_GetMainNetDistribution(&dist); + ck_assert_int_eq(err, SKY_OK); + err = SKY_params_Distribution_GetAddresses(dist, &all); + ck_assert_int_eq(err, SKY_OK); ck_assert(all.len == 100); // At the time of this writing, there should be 25 addresses in the // unlocked pool and 75 in the locked pool. - SKY_params_GetUnlockedDistributionAddresses(&unlocked); + err = SKY_params_Distribution_UnlockedAddresses(dist, &unlocked); + ck_assert_int_eq(err, SKY_OK); ck_assert(unlocked.len == 25); - SKY_params_GetLockedDistributionAddresses(&locked); + err = SKY_params_Distribution_LockedAddresses(dist, &locked); + ck_assert_int_eq(err, SKY_OK); ck_assert(locked.len == 75); int i, j, k; diff --git a/lib/cgo/tests/check_util.droplet.c b/lib/cgo/tests/check_util.droplet.c index 6ec6b6a27..b17f21e41 100644 --- a/lib/cgo/tests/check_util.droplet.c +++ b/lib/cgo/tests/check_util.droplet.c @@ -194,7 +194,7 @@ START_TEST(TestToString) { char buffer[BUFFER_SIZE]; char bufferNull[BUFFER_SIZE]; - GoString s = {buffer, 0}; + GoString_ s = {buffer, 0}; tmpstruct cases[] = { {.s = {"0.000000", 8}, .n = 0, .e = SKY_OK}, {.s = {"0.000001", 8}, .n = 1, .e = SKY_OK}, @@ -207,16 +207,15 @@ START_TEST(TestToString) }; int len = (sizeof(cases) / sizeof(tmpstruct)); - GoString nullStr = {bufferNull, 0}; int i; for (i = 0; i < len; i++) { tmpstruct tc = cases[i]; - int err = SKY_droplet_ToString(tc.n, (GoString_*)&s); + int err = SKY_droplet_ToString(tc.n, &s); if (tc.e == SKY_OK) { ck_assert(err == SKY_OK); - ck_assert_str_eq(tc.s.p, s.p); + ck_assert(isGoString_toGoStringEq(s, tc.s)); } else { ck_assert(err == tc.e); } diff --git a/lib/cgo/tests/cipher.testsuite.c b/lib/cgo/tests/cipher.testsuite.c index 784d27827..d4b59d10d 100644 --- a/lib/cgo/tests/cipher.testsuite.c +++ b/lib/cgo/tests/cipher.testsuite.c @@ -387,13 +387,13 @@ void ValidateSeedData(SeedTestData* seedData, InputTestData* inputData) { cipher__PubKey pubkey; cipher__SecKey seckey; - GoSlice keys; + GoSlice_ keys; // Force allocation of memory for slice buffer keys.len = keys.cap = 0; keys.data = NULL; - SKY_cipher_GenerateDeterministicKeyPairs(seedData->Seed, seedData->Keys.len, (GoSlice_*)&keys); + SKY_cipher_GenerateDeterministicKeyPairs(seedData->Seed, seedData->Keys.len, &keys); ck_assert_msg(keys.data != NULL, "SKY_cipher_GenerateDeterministicKeyPairs must allocate memory slice with zero cap"); @@ -444,7 +444,7 @@ void ValidateSeedData(SeedTestData* seedData, InputTestData* inputData) char bufferSecKey[101]; strnhex((unsigned char*)s, bufferSecKey, sizeof(cipher__SecKey)); GoSlice slseckey = {bufferSecKey, sizeof(cipher__SecKey), 65}; - validSec = SKY_secp256k1_VerifySecKey(slseckey); + validSec = SKY_secp256k1_VerifySecKey(slseckey); ck_assert_msg(validSec == 1, "SKY_secp256k1_VerifySeckey failed"); GoInt validPub; diff --git a/lib/cgo/tests/test_main.c b/lib/cgo/tests/test_main.c index 99b15a3b6..cb57f4e76 100644 --- a/lib/cgo/tests/test_main.c +++ b/lib/cgo/tests/test_main.c @@ -5,13 +5,18 @@ int main(void) { int number_failed = 0; int number_failed_fork = 0; - SRunner* sr = srunner_create(cipher_address()); + SRunner* sr = srunner_create(common_check_cipher_address()); SRunner* sr_fork = srunner_create(coin_transaction_fork()); + srunner_add_suite(sr, common_check_cipher_hash()); + srunner_add_suite(sr, common_check_cipher_crypto()); srunner_add_suite(sr, cipher_bitcoin()); srunner_add_suite(sr, cipher_crypto()); srunner_add_suite(sr, cipher_secp256k1()); srunner_add_suite(sr, cipher_encrypt_scrypt_chacha20poly1305()); srunner_add_suite(sr, cipher_hash()); + srunner_add_suite(sr, check_cipher_address()); + srunner_add_suite(sr, cipher_bip32()); + srunner_add_suite(sr, cipher_bip44()); srunner_add_suite(sr, coin_blocks()); srunner_add_suite(sr, coin_coin()); srunner_add_suite(sr, coin_math()); diff --git a/lib/cgo/tests/test_main.h b/lib/cgo/tests/test_main.h index 036046f81..9cf1259b0 100644 --- a/lib/cgo/tests/test_main.h +++ b/lib/cgo/tests/test_main.h @@ -10,14 +10,18 @@ #include "skytest.h" #include "skytypes.h" #include "skyerrors.h" +#include "test_main_common.h" Suite *cipher_bitcoin(void); Suite *cipher_address(void); +Suite *common_check_cipher_hash(void); Suite *cipher_testsuite(void); Suite *cipher_crypto(void); Suite *cipher_secp256k1(void); Suite *cipher_encrypt_scrypt_chacha20poly1305(void); Suite *cipher_hash(void); +Suite *cipher_bip32(void); +Suite *cipher_bip44(void); Suite *coin_blocks(void); Suite *coin_coin(void); Suite *coin_math(void); @@ -27,5 +31,6 @@ Suite *coin_transaction_fork(void); Suite *param_distribution(void); Suite *util_droplet(void); Suite *util_fee(void); +Suite* check_cipher_address(void); #endif \ No newline at end of file diff --git a/lib/cgo/tests/test_main_common.h b/lib/cgo/tests/test_main_common.h new file mode 100644 index 000000000..7bcd03c3f --- /dev/null +++ b/lib/cgo/tests/test_main_common.h @@ -0,0 +1,11 @@ +#ifndef TEST_MAIN_COMMON_H +#define TEST_MAIN_COMMON_H + +#include +#include + +Suite *common_check_cipher_hash(void); +Suite *common_check_cipher_address(void); +Suite *common_check_cipher_crypto(void); + +#endif // TEST_MAIN_COMMON_H diff --git a/lib/cgo/tests/test_main_hw.c b/lib/cgo/tests/test_main_hw.c new file mode 100644 index 000000000..e4d6593da --- /dev/null +++ b/lib/cgo/tests/test_main_hw.c @@ -0,0 +1,18 @@ +#include +#include + +#include "test_main_common.h" + +// run suite +int main(void) +{ + int number_failed = 0; + SRunner* sr = srunner_create(common_check_cipher_hash()); + srunner_add_suite(sr, common_check_cipher_address()); + srunner_add_suite(sr, common_check_cipher_crypto()); + srunner_run_all(sr, CK_VERBOSE); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + sr = NULL; + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/lib/cgo/tests/testutils/common.c b/lib/cgo/tests/testutils/common.c new file mode 100644 index 000000000..4c808c28a --- /dev/null +++ b/lib/cgo/tests/testutils/common.c @@ -0,0 +1,46 @@ +#include "common.h" + +#include +#include + +#include "libskycoin.h" +#include "skyerrors.h" + +int MEMPOOLIDX = 0; +void *MEMPOOL[1024 * 256]; + +GoInt_ isU8Eq(GoUint8_ p1[], GoUint8_ p2[], size_t len) +{ + for (GoInt i = 0; i < len; i++) { + if (p1[i] != p2[i]) { + return 0; + } + } + return 1; +} + +void* registerMemCleanup(void* p) +{ + int i; + for (i = 0; i < MEMPOOLIDX; i++) { + if (MEMPOOL[i] == NULL) { + MEMPOOL[i] = p; + return p; + } + } + MEMPOOL[MEMPOOLIDX++] = p; + return p; +} + +int copyGoSlice_toGoSlice(GoSlice* pdest, GoSlice_* psource, int elem_size) +{ + pdest->len = psource->len; + pdest->cap = psource->len; + int size = pdest->len * elem_size; + pdest->data = malloc(size); + if (pdest->data == NULL) + return SKY_ERROR; + registerMemCleanup(pdest->data); + memcpy(pdest->data, psource->data, size); + return SKY_OK; +} diff --git a/lib/cgo/tests/testutils/common.h b/lib/cgo/tests/testutils/common.h new file mode 100644 index 000000000..73754d49e --- /dev/null +++ b/lib/cgo/tests/testutils/common.h @@ -0,0 +1,9 @@ +#ifndef TEST_UTIL_COMMON +#define TEST_UTIL_COMMON + +#include +#include "skytypes.h" + +GoInt_ isU8Eq(GoUint8_ p1[], GoUint8_ p2[], size_t len); + +#endif // TEST_UTIL_COMMON diff --git a/lib/cgo/tests/testutils/libsky_assert.c b/lib/cgo/tests/testutils/libsky_assert.c index c8ff93338..6513ce8a3 100644 --- a/lib/cgo/tests/testutils/libsky_assert.c +++ b/lib/cgo/tests/testutils/libsky_assert.c @@ -1,144 +1,316 @@ - -#include "skyassert.h" -#include "skystring.h" -#include - - -GoInt_ equalSlices(GoSlice* slice1, GoSlice* slice2, int elem_size) -{ - if (slice1->len != slice2->len) - return 0; - return (memcmp(slice1->data, slice2->data, slice1->len * elem_size) == 0); -} - -GoInt_ equalSlices_(GoSlice_* slice1, GoSlice_* slice2, int elem_size) -{ - if (slice1->len != slice2->len) - return 0; - return (memcmp(slice1->data, slice2->data, slice1->len * elem_size) == 0); -} - -GoInt_ equalTransactions(coin__Transactions* pTxs1, coin__Transactions* pTxs2) -{ - if (pTxs1->len != pTxs2->len) - return 0; - coin__Transaction* pTx1 = pTxs1->data; - coin__Transaction* pTx2 = pTxs2->data; - int i; - for (i = 0; i < pTxs1->len; i++) { - if (!isTransactionEq(pTx1, pTx2)) - return 0; - pTx1++; - pTx2++; - } - return 1; -} - -GoInt_ isAddressEq(cipher__Address* addr1, cipher__Address* addr2) -{ - return (addr1->Version == addr2->Version && memcmp((void*)addr1, (void*)addr2, sizeof(cipher__Address)) == 0); -} - -GoInt_ isBitcoinAddressEq(cipher__BitcoinAddress* addr1, cipher__BitcoinAddress* addr2) -{ - return (addr1->Version == addr2->Version && memcmp((void*)addr1, (void*)addr2, sizeof(cipher__Address)) == 0); -} - -GoInt_ isGoStringEq(GoString string1, GoString string2) -{ - return (string1.n == string2.n) && - (strcmp(string1.p, string2.p) == 0); -} - -GoInt_ isGoString_Eq(GoString_ string1, GoString_ string2) -{ - return (string1.n == string2.n) && - (strcmp(string1.p, string2.p) == 0); -} - -GoInt_ isSecKeyEq(cipher__SecKey* seckey1, cipher__SecKey* seckey2) -{ - return memcmp((void*)seckey1, (void*)seckey2, sizeof(cipher__SecKey)) == 0; -} - -GoInt_ isPubKeyEq(cipher__PubKey* pubkey1, cipher__PubKey* pubkey2) -{ - return (memcmp((void*)pubkey1, (void*)pubkey2, sizeof(cipher__PubKey)) == 0); -} - -GoInt_ isSigEq(cipher__Sig* sig1, cipher__Sig* sig2) -{ - return memcmp((void*)sig1, (void*)sig2, sizeof(cipher__Sig)) == 0; -} - -GoInt_ isU8Eq(unsigned char p1[], unsigned char p2[], size_t len) -{ - for (GoInt i = 0; i < len; i++) { - if (p1[i] != p2[i]) { - return 0; - } - } - return 1; -} - -GoInt_ isSHA256Eq(cipher__SHA256* sh1, cipher__SHA256* sh2) -{ - return (memcmp((void*)sh1, (void*)sh1, sizeof(cipher__SHA256)) == 0); -} - -GoInt_ isGoSliceEq(GoSlice* slice1, GoSlice* slice2) -{ - return (slice1->len == slice2->len) && - (memcmp(slice1->data, slice2->data, slice1->len) == 0); -} - -GoInt_ isGoSlice_Eq(GoSlice_* slice1, GoSlice_* slice2) -{ - return (slice1->len == slice2->len) && - (memcmp(slice1->data, slice2->data, slice1->len) == 0); -} - -GoInt_ isTransactionsEq(coin__Transactions* x1, coin__Transactions* x2) -{ - return equalTransactions(x1, x2); -} - -GoInt_ isUxOutEq(coin__UxOut* x1, coin__UxOut* x2) -{ - return memcmp(x1, x2, sizeof(coin__UxOut)) == 0; -} - -GoInt_ isTransactionEq(coin__Transaction* x1, coin__Transaction* x2) -{ - if (x1->Length != x2->Length || - x1->Type != x2->Type) { - return 0; - } - if (!isSHA256Eq(&x1->InnerHash, &x2->InnerHash)) - return 0; - if (!equalSlices_(&x1->Sigs, &x2->Sigs, sizeof(cipher__Sig))) - return 0; - if (!equalSlices_(&x1->In, &x2->In, sizeof(cipher__SHA256))) - return 0; - // if (!equalSlices_(&x1->Out, &x2->Out, sizeof(coin__TransactionOutput))) - // return 0; - return 1; -} - -GoInt_ isTransactionOutputEq(coin__TransactionOutput* x1, - coin__TransactionOutput* x2) -{ - if (x1->Coins != x2->Coins || - x1->Hours != x2->Hours) { - return 0; - } - - if (!isAddressEq(&x1->Address, &x2->Address)) - return 0; - return 1; -} - -GoInt_ isUxArrayEq(coin__UxArray* slice1, coin__UxArray* slice2) -{ - return (memcmp(slice1->data, slice2->data, slice1->len) == 0) && ((slice1->len == slice2->len)); -} +#include "check.h" +#include "skyassert.h" +#include "skystring.h" +#include + +GoInt equalSlices(GoSlice* slice1, GoSlice* slice2, int elem_size) +{ + if (slice1->len != slice2->len) + return 0; + return (memcmp(slice1->data, slice2->data, slice1->len * elem_size) == 0); +} + +GoInt equalSlices_(GoSlice_* slice1, GoSlice_* slice2, int elem_size) +{ + if (slice1->len != slice2->len) + return 0; + return (memcmp(slice1->data, slice2->data, slice1->len * elem_size) == 0); +} + +GoInt equalTransactions(coin__Transactions* pTxs1, coin__Transactions* pTxs2) +{ + if (pTxs1->len != pTxs2->len) + return 0; + coin__Transaction* pTx1 = pTxs1->data; + coin__Transaction* pTx2 = pTxs2->data; + int i; + for (i = 0; i < pTxs1->len; i++) { + if (!isTransactionEq(pTx1, pTx2)) + return 0; + pTx1++; + pTx2++; + } + return 1; +} + +GoInt isBitcoinAddressEq(cipher__BitcoinAddress* addr1, cipher__BitcoinAddress* addr2) +{ + return (addr1->Version == addr2->Version && isRipemd160Eq(&addr1->Key, &addr2->Key)); +} + + +GoInt isSecKeyEq(cipher__SecKey* seckey1, cipher__SecKey* seckey2) +{ + return isU8Eq(*seckey1, *seckey2, sizeof(cipher__SecKey)); +} + +GoInt isSigEq(cipher__Sig* sig1, cipher__Sig* sig2) +{ + return isU8Eq(*sig1, *sig2, sizeof(cipher__Sig)); +} + +GoInt isSHA256Eq(cipher__SHA256* sh1, cipher__SHA256* sh2) +{ + return isU8Eq(*sh1, *sh2, sizeof(cipher__SHA256)); +} + +GoInt isGoSliceEq(GoSlice* slice1, GoSlice* slice2) +{ + return (slice1->len == slice2->len) && + (memcmp(slice1->data, slice2->data, slice1->len) == 0); +} + +GoInt isGoSlice_Eq(GoSlice_* slice1, GoSlice_* slice2) +{ + return (slice1->len == slice2->len) && + (memcmp(slice1->data, slice2->data, slice1->len) == 0); +} + +GoInt isTransactionsEq(coin__Transactions* x1, coin__Transactions* x2) +{ + return equalTransactions(x1, x2); +} + +GoInt isUxOutEq(coin__UxOut* x1, coin__UxOut* x2) +{ + return memcmp(x1, x2, sizeof(coin__UxOut)) == 0; +} + +GoInt isTransactionEq(coin__Transaction* x1, coin__Transaction* x2) +{ + if (x1->Length != x2->Length || x1->Type != x2->Type) { + return 0; + } + if (!isSHA256Eq(&x1->InnerHash, &x2->InnerHash)) + return 0; + if (!equalSlices_(&x1->Sigs, &x2->Sigs, sizeof(cipher__Sig))) + return 0; + if (!equalSlices_(&x1->In, &x2->In, sizeof(cipher__SHA256))) + return 0; + if (!equalSlices_(&x1->Out, &x2->Out, sizeof(coin__TransactionOutput))) + return 0; + return 1; +} + +GoInt isTransactionOutputEq(coin__TransactionOutput* x1, coin__TransactionOutput* x2) +{ + if (x1->Coins != x2->Coins || x1->Hours != x2->Hours) { + return 0; + } + + if (!isAddressEq(&x1->Address, &x2->Address)) + return 0; + return 1; +} + +GoInt isUxArrayEq(coin__UxArray* slice1, coin__UxArray* slice2) +{ + return (memcmp(slice1->data, slice2->data, slice1->len) == 0) && ((slice1->len == slice2->len)); +} + +GoInt isTransactionHandleEq(Transaction__Handle* handle1, Transaction__Handle* handle2) +{ + GoUint32 len1 = 0; + GoUint32 len2 = 0; + GoUint8 type1 = 0; + GoUint8 type2 = 0; + cipher__SHA256 sha1 = ""; + cipher__SHA256 sha2 = ""; + GoUint8 bufferP1[1024]; + GoUint8 bufferP2[1024]; + GoSlice_ p1 = {bufferP1, 0, 1024}; + GoSlice_ p2 = {bufferP2, 0, 1024}; + + GoUint32 err = SKY_coin_Transaction_GetLength(*handle1, &len1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_GetLength(*handle2, &len2); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_GetType(*handle1, &type1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_GetType(*handle2, &type2); + ck_assert_int_eq(err, SKY_OK); + + if (len1 != len2 || type1 != type2) { + return 0; + } + err = SKY_coin_Transaction_GetInnerHash(*handle1, &sha1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_GetInnerHash(*handle2, &sha2); + ck_assert_int_eq(err, SKY_OK); + if (!isSHA256Eq(&sha1, &sha2)) + return 0; + + err = SKY_coin_Transaction_GetSigs(*handle1, &p1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_GetSigs(*handle2, &p2); + ck_assert_int_eq(err, SKY_OK); + if (!equalSlices_(&p1, &p2, sizeof(cipher__Sig))) + return 0; + err = SKY_coin_Transaction_GetIn(*handle1, &p1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_GetIn(*handle2, &p2); + ck_assert_int_eq(err, SKY_OK); + if (!equalSlices_(&p1, &p2, sizeof(cipher__SHA256))) + return 0; + err = SKY_coin_Transaction_GetOut(*handle1, &p1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_coin_Transaction_GetOut(*handle2, &p2); + ck_assert_int_eq(err, SKY_OK); + if (!equalSlices_(&p1, &p2, sizeof(coin__TransactionOutput))) + return 0; + return 1; +} + +GoInt isPrivateKeyEq(PrivateKey__Handle handle1, PrivateKey__Handle handle2) +{ + GoUint8 bufferVersion1[1024]; + GoUint8 bufferVersion2[1024]; + GoSlice_ Version1 = {bufferVersion1, 0, 1024}; + GoSlice_ Version2 = {bufferVersion2, 0, 1024}; + GoUint8 bufferParentFingerprint1[1024]; + GoUint8 bufferParentFingerprint2[1024]; + GoSlice_ ParentFingerprint1 = {bufferParentFingerprint1, 0, 1024}; + GoSlice_ ParentFingerprint2 = {bufferParentFingerprint2, 0, 1024}; + GoUint32 childNumber1; + GoUint32 childNumber2; + GoUint8 bufferChainCode1[1024]; + GoUint8 bufferChainCode2[1024]; + GoSlice_ ChainCode1 = {bufferChainCode1, 0, 1024}; + GoSlice_ ChainCode2 = {bufferChainCode2, 0, 1024}; + GoUint8 bufferKey1[1024]; + GoUint8 bufferKey2[1024]; + GoSlice_ Key1 = {bufferKey1, 0, 1024}; + GoSlice_ Key2 = {bufferKey2, 0, 1024}; + GoUint8 Depth1; + GoUint8 Depth2; + + GoUint32 err = SKY_bip32_PrivateKey_GetVersion(handle1, &Version1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_GetVersion(handle2, &Version2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&Version1, &Version2)) { + printf("Version not equal\n"); + return 0; + } + + err = SKY_bip32_PrivateKey_GetDepth(handle1, &Depth1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_GetDepth(handle2, &Depth2); + ck_assert_int_eq(err, SKY_OK); + if (Depth1 != Depth2) { + printf("Depth not equal\n"); + return 0; + } + + err = SKY_bip32_PrivateKey_GetParentFingerprint(handle1, &ParentFingerprint1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_GetParentFingerprint(handle2, &ParentFingerprint2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&ParentFingerprint1, &ParentFingerprint2)) { + printf("ParentFingerprint not equal\n"); + return 0; + } + + err = SKY_bip32_PrivateKey_ChildNumber(handle1, &childNumber1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_ChildNumber(handle2, &childNumber2); + ck_assert_int_eq(err, SKY_OK); + if (childNumber1 != childNumber2) { + printf("childNumber not equal\n"); + return 0; + } + + err = SKY_bip32_PrivateKey_GetChainCode(handle1, &ChainCode1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_GetChainCode(handle2, &ChainCode2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&ChainCode1, &ChainCode2)) { + printf("ChainCode not equal\n"); + return 0; + } + + err = SKY_bip32_PrivateKey_GetKey(handle1, &Key1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PrivateKey_GetKey(handle2, &Key2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&Key1, &Key2)) { + printf("Key not equal\n"); + return 0; + } + + return 1; +} + +GoInt isPublicKeyEq(PublicKey__Handle handle1, PublicKey__Handle handle2) +{ + GoUint8 bufferVersion1[1024]; + GoUint8 bufferVersion2[1024]; + GoSlice_ Version1 = {bufferVersion1, 0, 1024}; + GoSlice_ Version2 = {bufferVersion2, 0, 1024}; + GoUint8 bufferParentFingerprint1[1024]; + GoUint8 bufferParentFingerprint2[1024]; + GoSlice_ ParentFingerprint1 = {bufferParentFingerprint1, 0, 1024}; + GoSlice_ ParentFingerprint2 = {bufferParentFingerprint2, 0, 1024}; + GoUint32 childNumber1; + GoUint32 childNumber2; + GoUint8 bufferChainCode1[1024]; + GoUint8 bufferChainCode2[1024]; + GoSlice_ ChainCode1 = {bufferChainCode1, 0, 1024}; + GoSlice_ ChainCode2 = {bufferChainCode2, 0, 1024}; + GoUint8 bufferKey1[1024]; + GoUint8 bufferKey2[1024]; + GoSlice_ Key1 = {bufferKey1, 0, 1024}; + GoSlice_ Key2 = {bufferKey2, 0, 1024}; + GoUint8 Depth1; + GoUint8 Depth2; + + GoUint32 err = SKY_bip32_PublicKey_GetVersion(handle1, &Version1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_GetVersion(handle2, &Version2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&Version1, &Version2)) { + return 0; + } + + err = SKY_bip32_PublicKey_GetDepth(handle1, &Depth1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_GetDepth(handle2, &Depth2); + ck_assert_int_eq(err, SKY_OK); + if (Depth1 != Depth2) { + return 0; + } + + err = SKY_bip32_PublicKey_GetParentFingerprint(handle1, &ParentFingerprint1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_GetParentFingerprint(handle2, &ParentFingerprint2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&ParentFingerprint1, &ParentFingerprint2)) { + return 0; + } + + err = SKY_bip32_PublicKey_ChildNumber(handle1, &childNumber1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_ChildNumber(handle2, &childNumber2); + ck_assert_int_eq(err, SKY_OK); + if (childNumber1 != childNumber2) { + return 0; + } + + err = SKY_bip32_PublicKey_GetChainCode(handle1, &ChainCode1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_GetChainCode(handle2, &ChainCode2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&ChainCode1, &ChainCode2)) { + return 0; + } + + err = SKY_bip32_PublicKey_GetKey(handle1, &Key1); + ck_assert_int_eq(err, SKY_OK); + err = SKY_bip32_PublicKey_GetKey(handle2, &Key2); + ck_assert_int_eq(err, SKY_OK); + if (!isGoSlice_Eq(&Key1, &Key2)) { + return 0; + } + + return 1; +} diff --git a/lib/cgo/tests/testutils/libsky_assert.common.c b/lib/cgo/tests/testutils/libsky_assert.common.c new file mode 100644 index 000000000..38d4d09dd --- /dev/null +++ b/lib/cgo/tests/testutils/libsky_assert.common.c @@ -0,0 +1,37 @@ +#include "check.h" +#include "skyassert.h" +#include "skystring.h" +#include + +GoInt isAddressEq(cipher__Address* addr1, cipher__Address* addr2) +{ + return (addr1->Version == addr2->Version && isRipemd160Eq(&addr1->Key, &addr2->Key)); +} + +GoInt isGoStringEq(GoString string1, GoString string2) +{ + return (string1.n == string2.n) && + (strncmp(string1.p, string2.p, string1.n) == 0); +} + +GoInt isGoString_Eq(GoString_ string1, GoString_ string2) +{ + return (string1.n == string2.n) && + (strncmp(string1.p, string2.p, string1.n) == 0); +} + +GoInt isGoString_toGoStringEq(GoString_ string1, GoString string2) +{ + return (string1.n == string2.n) && + (strncmp(string1.p, string2.p, string2.n) == 0); +} + +GoInt isPubKeyEq(cipher__PubKey* pubkey1, cipher__PubKey* pubkey2) +{ + return isU8Eq(*pubkey1, *pubkey2, sizeof(cipher__PubKey)); +} + +GoInt isRipemd160Eq(cipher__Ripemd160* rip1, cipher__Ripemd160* rip2) +{ + return isU8Eq(*rip1, *rip2, sizeof(cipher__Ripemd160)); +} diff --git a/lib/cgo/tests/testutils/libsky_testutil.c b/lib/cgo/tests/testutils/libsky_testutil.c index d7994d383..86bda5426 100644 --- a/lib/cgo/tests/testutils/libsky_testutil.c +++ b/lib/cgo/tests/testutils/libsky_testutil.c @@ -1,14 +1,13 @@ - -#include -#include +#include "json.h" +#include "libskycoin.h" +#include "skyerrors.h" +#include "skytest.h" +#include "skytypes.h" #include +#include #include +#include #include -#include "json.h" -#include "skytypes.h" -#include "skytest.h" -#include "skyerrors.h" -#include "libskycoin.h" #define BUFFER_SIZE 1024 #define stableWalletName "integration-test.wlt" #define STRING_SIZE 128 @@ -20,8 +19,8 @@ //Define function SKY_handle_close to avoid including libskycoin.h void SKY_handle_close(Handle p0); -int MEMPOOLIDX = 0; -void *MEMPOOL[1024 * 256]; +extern int MEMPOOLIDX; +extern void* MEMPOOL[1024 * 256]; int JSONPOOLIDX = 0; json_value* JSON_POOL[128]; @@ -30,8 +29,8 @@ int HANDLEPOOLIDX = 0; Handle HANDLE_POOL[128]; typedef struct { - Client__Handle client; - WalletResponse__Handle wallet; + Client__Handle client; + WalletResponse__Handle wallet; } wallet_register; int WALLETPOOLIDX = 0; @@ -40,302 +39,344 @@ wallet_register WALLET_POOL[64]; int stdout_backup; int pipefd[2]; -void * registerMemCleanup(void *p) { - int i; - for (i = 0; i < MEMPOOLIDX; i++) { - if(MEMPOOL[i] == NULL){ - MEMPOOL[i] = p; - return p; +void freeRegisteredMemCleanup(void* p) +{ + int i; + for (i = 0; i < MEMPOOLIDX; i++) { + if (MEMPOOL[i] == p) { + free(p); + MEMPOOL[i] = NULL; + break; + } } - } - MEMPOOL[MEMPOOLIDX++] = p; - return p; } -void freeRegisteredMemCleanup(void *p){ - int i; - for (i = 0; i < MEMPOOLIDX; i++) { - if(MEMPOOL[i] == p){ - free(p); - MEMPOOL[i] = NULL; - break; +int registerJsonFree(void* p) +{ + int i; + for (i = 0; i < JSONPOOLIDX; i++) { + if (JSON_POOL[i] == NULL) { + JSON_POOL[i] = p; + return i; + } } - } + JSON_POOL[JSONPOOLIDX++] = p; + return JSONPOOLIDX - 1; } -int registerJsonFree(void *p){ - int i; - for (i = 0; i < JSONPOOLIDX; i++) { - if(JSON_POOL[i] == NULL){ - JSON_POOL[i] = p; - return i; +void freeRegisteredJson(void* p) +{ + int i; + for (i = 0; i < JSONPOOLIDX; i++) { + if (JSON_POOL[i] == p) { + JSON_POOL[i] = NULL; + json_value_free((json_value*)p); + break; + } } - } - JSON_POOL[JSONPOOLIDX++] = p; - return JSONPOOLIDX-1; -} - -void freeRegisteredJson(void *p){ - int i; - for (i = 0; i < JSONPOOLIDX; i++) { - if(JSON_POOL[i] == p){ - JSON_POOL[i] = NULL; - json_value_free( (json_value*)p ); - break; - } - } } int registerWalletClean(Client__Handle clientHandle, - WalletResponse__Handle walletHandle){ - int i; - for (i = 0; i < WALLETPOOLIDX; i++) { - if(WALLET_POOL[i].wallet == 0 && WALLET_POOL[i].client == 0){ - WALLET_POOL[i].wallet = walletHandle; - WALLET_POOL[i].client = clientHandle; - return i; + WalletResponse__Handle walletHandle) +{ + int i; + for (i = 0; i < WALLETPOOLIDX; i++) { + if (WALLET_POOL[i].wallet == 0 && WALLET_POOL[i].client == 0) { + WALLET_POOL[i].wallet = walletHandle; + WALLET_POOL[i].client = clientHandle; + return i; + } } - } - WALLET_POOL[WALLETPOOLIDX].wallet = walletHandle; - WALLET_POOL[WALLETPOOLIDX].client = clientHandle; - return WALLETPOOLIDX++; + WALLET_POOL[WALLETPOOLIDX].wallet = walletHandle; + WALLET_POOL[WALLETPOOLIDX].client = clientHandle; + return WALLETPOOLIDX++; } -int registerHandleClose(Handle handle){ - int i; - for (i = 0; i < HANDLEPOOLIDX; i++) { - if(HANDLE_POOL[i] == 0){ - HANDLE_POOL[i] = handle; - return i; +int registerHandleClose(Handle handle) +{ + int i; + for (i = 0; i < HANDLEPOOLIDX; i++) { + if (HANDLE_POOL[i] == 0) { + HANDLE_POOL[i] = handle; + return i; + } } - } - HANDLE_POOL[HANDLEPOOLIDX++] = handle; - return HANDLEPOOLIDX - 1; + HANDLE_POOL[HANDLEPOOLIDX++] = handle; + return HANDLEPOOLIDX - 1; } -void closeRegisteredHandle(Handle handle){ - int i; - for (i = 0; i < HANDLEPOOLIDX; i++) { - if(HANDLE_POOL[i] == handle){ - HANDLE_POOL[i] = 0; - SKY_handle_close(handle); - break; +void closeRegisteredHandle(Handle handle) +{ + int i; + for (i = 0; i < HANDLEPOOLIDX; i++) { + if (HANDLE_POOL[i] == handle) { + HANDLE_POOL[i] = 0; + SKY_handle_close(handle); + break; + } } - } } -void cleanupWallet(Client__Handle client, WalletResponse__Handle wallet){ - int result; - GoString_ strWalletDir; - GoString_ strFileName; - memset(&strWalletDir, 0, sizeof(GoString_)); - memset(&strFileName, 0, sizeof(GoString_)); - - - result = SKY_api_Handle_Client_GetWalletDir(client, &strWalletDir); - if( result != SKY_OK ){ - return; - } - result = SKY_api_Handle_Client_GetWalletFileName(wallet, &strFileName); - if( result != SKY_OK ){ - free( (void*)strWalletDir.p ); - return; - } - char fullPath[128]; - if( strWalletDir.n + strFileName.n < 126){ - strcpy( fullPath, strWalletDir.p ); - if( fullPath[0] == 0 || fullPath[strlen(fullPath) - 1] != '/' ) - strcat(fullPath, "/"); - strcat( fullPath, strFileName.p ); - result = unlink( fullPath ); - if( strlen(fullPath) < 123 ){ - strcat( fullPath, ".bak" ); - result = unlink( fullPath ); +void cleanupWallet(Client__Handle client, WalletResponse__Handle wallet) +{ + int result; + GoString_ strWalletDir; + GoString_ strFileName; + memset(&strWalletDir, 0, sizeof(GoString_)); + memset(&strFileName, 0, sizeof(GoString_)); + + + result = SKY_api_Handle_Client_GetWalletDir(client, &strWalletDir); + if (result != SKY_OK) { + return; } - } - GoString str = { strFileName.p, strFileName.n }; - result = SKY_api_Client_UnloadWallet( client, str ); - GoString strFullPath = { fullPath, strlen(fullPath) }; - free( (void*)strWalletDir.p ); - free( (void*)strFileName.p ); + result = SKY_api_Handle_Client_GetWalletFileName(wallet, &strFileName); + if (result != SKY_OK) { + free((void*)strWalletDir.p); + return; + } + char fullPath[128]; + if (strWalletDir.n + strFileName.n < 126) { + strcpy(fullPath, strWalletDir.p); + if (fullPath[0] == 0 || fullPath[strlen(fullPath) - 1] != '/') + strcat(fullPath, "/"); + strcat(fullPath, strFileName.p); + result = unlink(fullPath); + if (strlen(fullPath) < 123) { + strcat(fullPath, ".bak"); + result = unlink(fullPath); + } + } + GoString str = {strFileName.p, strFileName.n}; + result = SKY_api_Client_UnloadWallet(client, str); + GoString strFullPath = {fullPath, strlen(fullPath)}; + free((void*)strWalletDir.p); + free((void*)strFileName.p); } void cleanRegisteredWallet( - Client__Handle client, - WalletResponse__Handle wallet){ - - int i; - for (i = 0; i < WALLETPOOLIDX; i++) { - if(WALLET_POOL[i].wallet == wallet && WALLET_POOL[i].client == client){ - WALLET_POOL[i].wallet = 0; - WALLET_POOL[i].client = 0; - cleanupWallet( client, wallet ); - return; + Client__Handle client, + WalletResponse__Handle wallet) +{ + int i; + for (i = 0; i < WALLETPOOLIDX; i++) { + if (WALLET_POOL[i].wallet == wallet && WALLET_POOL[i].client == client) { + WALLET_POOL[i].wallet = 0; + WALLET_POOL[i].client = 0; + cleanupWallet(client, wallet); + return; + } } - } } -void cleanupMem() { - int i; +void cleanupMem() +{ + int i; - for (i = 0; i < WALLETPOOLIDX; i++) { - if(WALLET_POOL[i].client != 0 && WALLET_POOL[i].wallet != 0){ - cleanupWallet( WALLET_POOL[i].client, WALLET_POOL[i].wallet ); + for (i = 0; i < WALLETPOOLIDX; i++) { + if (WALLET_POOL[i].client != 0 && WALLET_POOL[i].wallet != 0) { + cleanupWallet(WALLET_POOL[i].client, WALLET_POOL[i].wallet); + } + } + + void** ptr; + for (i = MEMPOOLIDX, ptr = MEMPOOL; i; --i) { + if (*ptr) + memset(ptr, 0, sizeof(void*)); + ptr++; + } + for (i = JSONPOOLIDX, ptr = (void*)JSON_POOL; i; --i) { + if (*ptr) + json_value_free(*ptr); + ptr++; + } + for (i = 0; i < HANDLEPOOLIDX; i++) { + if (HANDLE_POOL[i]) + SKY_handle_close(HANDLE_POOL[i]); } - } - - void **ptr; - for (i = MEMPOOLIDX, ptr = MEMPOOL; i; --i) { - if( *ptr ) - memset(ptr, 0, sizeof(void *)); - ptr++; - } - for (i = JSONPOOLIDX, ptr = (void*)JSON_POOL; i; --i) { - if( *ptr ) - json_value_free(*ptr); - ptr++; - } - for (i = 0; i < HANDLEPOOLIDX; i++) { - if( HANDLE_POOL[i] ) - SKY_handle_close(HANDLE_POOL[i]); - } } -json_value* loadJsonFile(const char* filename){ - FILE *fp; - struct stat filestatus; - int file_size; - char* file_contents; - json_char* json; - json_value* value; - - if ( stat(filename, &filestatus) != 0) { - return NULL; - } - file_size = filestatus.st_size; - file_contents = (char*)malloc(filestatus.st_size); - if ( file_contents == NULL) { - return NULL; - } - fp = fopen(filename, "rt"); - if (fp == NULL) { - free(file_contents); - return NULL; - } - if ( fread(file_contents, file_size, 1, fp) != 1 ) { +json_value* loadJsonFile(const char* filename) +{ + FILE* fp; + struct stat filestatus; + int file_size; + char* file_contents; + json_char* json; + json_value* value; + + if (stat(filename, &filestatus) != 0) { + return NULL; + } + file_size = filestatus.st_size; + file_contents = (char*)malloc(filestatus.st_size); + if (file_contents == NULL) { + return NULL; + } + fp = fopen(filename, "rt"); + if (fp == NULL) { + free(file_contents); + return NULL; + } + if (fread(file_contents, file_size, 1, fp) != 1) { + fclose(fp); + free(file_contents); + return NULL; + } fclose(fp); + + json = (json_char*)file_contents; + value = json_parse(json, file_size); free(file_contents); - return NULL; - } - fclose(fp); - - json = (json_char*)file_contents; - value = json_parse(json, file_size); - free(file_contents); - return value; + return value; } void setup(void) { srand(time(NULL)); } -void teardown(void) { - cleanupMem(); +void teardown(void) +{ + cleanupMem(); } // TODO: Move to libsky_io.c -void fprintbuff(FILE *f, void *buff, size_t n) { - unsigned char *ptr = (unsigned char *) buff; - fprintf(f, "[ "); - for (; n; --n, ptr++) { - fprintf(f, "%02d ", *ptr); - } - fprintf(f, "]"); +void fprintbuff(FILE* f, void* buff, size_t n) +{ + unsigned char* ptr = (unsigned char*)buff; + fprintf(f, "[ "); + for (; n; --n, ptr++) { + fprintf(f, "%02d ", *ptr); + } + fprintf(f, "]"); } -int parseBoolean(const char* str, int length){ - int result = 0; - if(length == 1){ - result = str[0] == '1' || str[0] == 't' || str[0] == 'T'; - } else { - result = strncmp(str, "true", length) == 0 || - strncmp(str, "True", length) == 0 || - strncmp(str, "TRUE", length) == 0; - } - return result; +int parseBoolean(const char* str, int length) +{ + int result = 0; + if (length == 1) { + result = str[0] == '1' || str[0] == 't' || str[0] == 'T'; + } else { + result = strncmp(str, "true", length) == 0 || + strncmp(str, "True", length) == 0 || + strncmp(str, "TRUE", length) == 0; + } + return result; } -int copySlice(GoSlice_* pdest, GoSlice_* psource, int elem_size){ - pdest->len = psource->len; - pdest->cap = psource->len; - int size = pdest->len * elem_size; - pdest->data = malloc(size); - if( pdest->data == NULL ) - return SKY_ERROR; - registerMemCleanup( pdest->data ); - memcpy(pdest->data, psource->data, size ); - return SKY_OK; +int copySlice(GoSlice_* pdest, GoSlice_* psource, int elem_size) +{ + pdest->len = psource->len; + pdest->cap = psource->len; + int size = pdest->len * elem_size; + pdest->data = malloc(size); + if (pdest->data == NULL) + return SKY_ERROR; + registerMemCleanup(pdest->data); + memcpy(pdest->data, psource->data, size); + return SKY_OK; } -int copyGoSlice_toGoSlice(GoSlice* pdest, GoSlice_* psource, int elem_size){ - pdest->len = psource->len; - pdest->cap = psource->len; - int size = pdest->len * elem_size; - pdest->data = malloc(size); - if( pdest->data == NULL ) - return SKY_ERROR; - registerMemCleanup( pdest->data ); - memcpy(pdest->data, psource->data, size ); - return SKY_OK; +int copycoin_UxArraytoGoSlice(GoSlice* pdest, coin__UxArray* psource, int elem_size) +{ + pdest->len = psource->len; + pdest->cap = psource->len; + int size = pdest->len * elem_size; + pdest->data = malloc(size); + if (pdest->data == NULL) + return SKY_ERROR; + registerMemCleanup(pdest->data); + memcpy(pdest->data, psource->data, size); + return SKY_OK; } -int copycoin_UxArraytoGoSlice(GoSlice* pdest, coin__UxArray* psource, int elem_size){ - pdest->len = psource->len; - pdest->cap = psource->len; - int size = pdest->len * elem_size; - pdest->data = malloc(size); - if( pdest->data == NULL ) - return SKY_ERROR; - registerMemCleanup( pdest->data ); - memcpy(pdest->data, psource->data, size ); - return SKY_OK; +int cutSlice(GoSlice_* slice, int start, int end, int elem_size, GoSlice_* result) +{ + int size = end - start; + if (size <= 0) + return SKY_ERROR; + void* data = malloc(size * elem_size); + if (data == NULL) + return SKY_ERROR; + registerMemCleanup(data); + result->data = data; + result->len = size; + result->cap = size; + char* p = slice->data; + p += (elem_size * start); + memcpy(data, p, elem_size * size); + return SKY_OK; +} +int cutUxArray(coin__UxArray* slice, int start, int end, int elem_size, coin__UxArray* result) +{ + int size = end - start; + if (size <= 0) + return SKY_ERROR; + void* data = malloc(size * elem_size); + if (data == NULL) + return SKY_ERROR; + registerMemCleanup(data); + result->data = data; + result->len = size; + result->cap = size; + char* p = slice->data; + p += (elem_size * start); + memcpy(data, p, elem_size * size); + return SKY_OK; } -int cutSlice(GoSlice_* slice, int start, int end, int elem_size, GoSlice_* result){ - int size = end - start; - if( size <= 0) - return SKY_ERROR; - void* data = malloc(size * elem_size); - if( data == NULL ) - return SKY_ERROR; - registerMemCleanup( data ); - result->data = data; - result->len = size; - result->cap = size; - char* p = slice->data; - p += (elem_size * start); - memcpy( data, p, elem_size * size ); - return SKY_OK; +int concatSlices(GoSlice_* slice1, GoSlice_* slice2, int elem_size, GoSlice_* result) +{ + int size1 = slice1->len; + int size2 = slice2->len; + int size = size1 + size2; + if (size <= 0) + return SKY_ERROR; + void* data = malloc(size * elem_size); + if (data == NULL) + return SKY_ERROR; + registerMemCleanup(data); + result->data = data; + result->len = size; + result->cap = size; + char* p = data; + if (size1 > 0) { + memcpy(p, slice1->data, size1 * elem_size); + p += (elem_size * size1); + } + if (size2 > 0) { + memcpy(p, slice2->data, size2 * elem_size); + } + return SKY_OK; } -int concatSlices(GoSlice_* slice1, GoSlice_* slice2, int elem_size, GoSlice_* result){ - int size1 = slice1->len; - int size2 = slice2->len; - int size = size1 + size2; - if (size <= 0) - return SKY_ERROR; - void* data = malloc(size * elem_size); - if( data == NULL ) - return SKY_ERROR; - registerMemCleanup( data ); - result->data = data; - result->len = size; - result->cap = size; - char* p = data; - if(size1 > 0){ - memcpy( p, slice1->data, size1 * elem_size ); - p += (elem_size * size1); - } - if(size2 > 0){ - memcpy( p, slice2->data, size2 * elem_size ); - } - return SKY_OK; +int concatUxArray(coin__UxArray* slice1, coin__UxArray* slice2, int elem_size, coin__UxArray* result) +{ + { + int size1 = slice1->len; + int size2 = slice2->len; + int size = size1 + size2; + if (size <= 0) + return SKY_ERROR; + void* data = malloc(size * elem_size); + if (data == NULL) + return SKY_ERROR; + registerMemCleanup(data); + result->data = data; + result->len = size; + result->cap = size; + char* p = data; + if (size1 > 0) { + memcpy(p, slice1->data, size1 * elem_size); + p += (elem_size * size1); + } + if (size2 > 0) { + memcpy(p, slice2->data, size2 * elem_size); + } + return SKY_OK; + } } + +int copyGoStringtoGoString_(GoString* pdest, GoString_* psource) +{ + pdest->n = psource->p; + strncpy(pdest->p, psource->p, psource->n); +} \ No newline at end of file diff --git a/lib/cgo/tests/testutils/transutils.c b/lib/cgo/tests/testutils/transutils.c index ee59dfde6..bdac61377 100644 --- a/lib/cgo/tests/testutils/transutils.c +++ b/lib/cgo/tests/testutils/transutils.c @@ -9,269 +9,247 @@ #include "skytxn.h" #include -GoUint32_ zeroFeeCalculator(Transaction__Handle handle, GoUint64_ *pFee, - void *context) +GoUint32_ zeroFeeCalculator(Transaction__Handle handle, GoUint64_* pFee, void* context) { - *pFee = 0; - return SKY_OK; + *pFee = 0; + return SKY_OK; } -GoUint32_ makeKeysAndAddress(cipher__PubKey *ppubkey, cipher__SecKey *pseckey, - cipher__Address *paddress) +GoUint32_ makeKeysAndAddress(cipher__PubKey* ppubkey, cipher__SecKey* pseckey, cipher__Address* paddress) { - GoUint32_ result; - result = SKY_cipher_GenerateKeyPair(ppubkey, pseckey); - ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); - result = SKY_cipher_AddressFromPubKey(ppubkey, paddress); - ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); - return result; + GoUint32_ result; + result = SKY_cipher_GenerateKeyPair(ppubkey, pseckey); + ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); + result = SKY_cipher_AddressFromPubKey(ppubkey, paddress); + ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); + return result; } -GoUint32_ makeUxBodyWithSecret(coin__UxBody *puxBody, cipher__SecKey *pseckey) { - cipher__PubKey pubkey; - cipher__Address address; - GoUint32_ result; - - memset(puxBody, 0, sizeof(coin__UxBody)); - puxBody->Coins = 1000000; - puxBody->Hours = 100; - - result = SKY_cipher_GenerateKeyPair(&pubkey, pseckey); - ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); - result = SKY_cipher_PubKey_Verify(&pubkey); - ck_assert_msg(result == SKY_OK, "SKY_cipher_PubKey_Verify failed"); - result = SKY_cipher_SecKey_Verify(pseckey); - ck_assert_msg(result == SKY_OK, "Fail SKY_cipher_SecKey_Verify "); - char buff[1024]; - GoSlice slice = {buff, 0, 1024}; - cipher__SHA256 hash; - - randBytes(&slice, 128); - registerMemCleanup(slice.data); - result = SKY_cipher_SumSHA256(slice, &puxBody->SrcTransaction); - ck_assert_msg(result == SKY_OK, "SKY_cipher_SumSHA256 failed"); - - result = SKY_cipher_AddressFromPubKey(&pubkey, &puxBody->Address); - ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); - result = SKY_cipher_Address_Verify(&puxBody->Address,&pubkey); - ck_assert_msg(result == SKY_OK, "SKY_cipher_Address_Verify failed"); - return result; +GoUint32_ makeUxBodyWithSecret(coin__UxBody* puxBody, cipher__SecKey* pseckey) +{ + cipher__PubKey pubkey; + cipher__Address address; + GoUint32_ result; + + memset(puxBody, 0, sizeof(coin__UxBody)); + puxBody->Coins = 1000000; + puxBody->Hours = 100; + + result = SKY_cipher_GenerateKeyPair(&pubkey, pseckey); + ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); + result = SKY_cipher_PubKey_Verify(&pubkey); + ck_assert_msg(result == SKY_OK, "SKY_cipher_PubKey_Verify failed"); + result = SKY_cipher_SecKey_Verify(pseckey); + ck_assert_msg(result == SKY_OK, "Fail SKY_cipher_SecKey_Verify "); + char buff[1024]; + GoSlice slice = {buff, 0, 1024}; + cipher__SHA256 hash; + + randBytes(&slice, 128); + registerMemCleanup(slice.data); + result = SKY_cipher_SumSHA256(slice, &puxBody->SrcTransaction); + ck_assert_msg(result == SKY_OK, "SKY_cipher_SumSHA256 failed"); + + result = SKY_cipher_AddressFromPubKey(&pubkey, &puxBody->Address); + ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); + result = SKY_cipher_Address_Verify(&puxBody->Address, &pubkey); + ck_assert_msg(result == SKY_OK, "SKY_cipher_Address_Verify failed"); + return result; } -GoUint32_ makeUxOutWithSecret(coin__UxOut *puxOut, cipher__SecKey *pseckey) { - GoUint32_ result; - memset(puxOut, 0, sizeof(coin__UxOut)); - result = makeUxBodyWithSecret(&puxOut->Body, pseckey); - puxOut->Head.Time = 100; - puxOut->Head.BkSeq = 2; - result = SKY_cipher_SecKey_Verify(pseckey); - ck_assert_msg(result == SKY_OK, "SKY_cipher_SecKey_Verify failed"); - return result; - +GoUint32_ makeUxOutWithSecret(coin__UxOut* puxOut, cipher__SecKey* pseckey) +{ + GoUint32_ result; + memset(puxOut, 0, sizeof(coin__UxOut)); + result = makeUxBodyWithSecret(&puxOut->Body, pseckey); + puxOut->Head.Time = 100; + puxOut->Head.BkSeq = 2; + result = SKY_cipher_SecKey_Verify(pseckey); + ck_assert_msg(result == SKY_OK, "SKY_cipher_SecKey_Verify failed"); + return result; } -GoUint32_ makeUxBody(coin__UxBody *puxBody) { - cipher__SecKey seckey; - return makeUxBodyWithSecret(puxBody, &seckey); +GoUint32_ makeUxBody(coin__UxBody* puxBody) +{ + cipher__SecKey seckey; + return makeUxBodyWithSecret(puxBody, &seckey); } -GoUint32_ makeUxOut(coin__UxOut *puxOut) { - cipher__SecKey seckey; - return makeUxOutWithSecret(puxOut, &seckey); +GoUint32_ makeUxOut(coin__UxOut* puxOut) +{ + cipher__SecKey seckey; + return makeUxOutWithSecret(puxOut, &seckey); } -GoUint32_ makeAddress(cipher__Address *paddress) { - cipher__PubKey pubkey; - cipher__SecKey seckey; - cipher__Address address; - GoUint32_ result; +GoUint32_ makeAddress(cipher__Address* paddress) +{ + cipher__PubKey pubkey; + cipher__SecKey seckey; + cipher__Address address; + GoUint32_ result; - result = SKY_cipher_GenerateKeyPair(&pubkey, &seckey); - ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); + result = SKY_cipher_GenerateKeyPair(&pubkey, &seckey); + ck_assert_msg(result == SKY_OK, "SKY_cipher_GenerateKeyPair failed"); - result = SKY_cipher_AddressFromPubKey(&pubkey, paddress); - ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); - return result; + result = SKY_cipher_AddressFromPubKey(&pubkey, paddress); + ck_assert_msg(result == SKY_OK, "SKY_cipher_AddressFromPubKey failed"); + return result; } -coin__Transaction *makeTransactionFromUxOut(coin__UxOut *puxOut, - cipher__SecKey *pseckey, - Transaction__Handle *handle) +void makeTransactionFromUxOut(coin__UxOut* puxOut, cipher__SecKey* pseckey, Transaction__Handle* handle) { - GoUint32_ result; - coin__Transaction *ptransaction = NULL; - *handle = 0; - result = SKY_coin_Create_Transaction(handle); - ck_assert_msg(result == SKY_OK, "SKY_coin_Create_Transaction failed"); - registerHandleClose(*handle); - - cipher__SHA256 sha256; - result = SKY_coin_UxOut_Hash(puxOut, &sha256); - ck_assert_msg(result == SKY_OK, "SKY_coin_UxOut_Hash failed"); - GoUint16 r; - result = SKY_coin_Transaction_PushInput(*handle, &sha256); - ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_PushInput failed"); - - cipher__Address address1, address2; - result = makeAddress(&address1); - ck_assert_msg(result == SKY_OK, "makeAddress failed"); - result = makeAddress(&address2); - ck_assert_msg(result == SKY_OK, "makeAddress failed"); - - result = SKY_coin_Transaction_PushOutput(*handle, &address1, 1000000, 50); - ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_PushOutput failed"); - result = SKY_coin_Transaction_PushOutput(*handle, &address2, 5000000, 50); - ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_PushOutput failed"); - - GoSlice secKeys = {pseckey, 1, 1}; - result = SKY_coin_Transaction_SignInputs(*handle, secKeys); - ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_SignInputs failed"); - result = SKY_coin_Transaction_UpdateHeader(*handle); - ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_UpdateHeader failed"); - result = SKY_coin_GetTransactionObject(*handle, &ptransaction); - ck_assert_msg(result == SKY_OK, "SKY_coin_GetTransactionObject failed"); - registerMemCleanup(ptransaction); - return ptransaction; + GoUint32_ result; + *handle = 0; + result = SKY_coin_Create_Transaction(handle); + ck_assert_msg(result == SKY_OK, "SKY_coin_Create_Transaction failed"); + registerHandleClose(*handle); + + cipher__SHA256 sha256; + result = SKY_coin_UxOut_Hash(puxOut, &sha256); + ck_assert_msg(result == SKY_OK, "SKY_coin_UxOut_Hash failed"); + GoUint16 r; + result = SKY_coin_Transaction_PushInput(*handle, &sha256); + ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_PushInput failed"); + + cipher__Address address1, address2; + result = makeAddress(&address1); + ck_assert_msg(result == SKY_OK, "makeAddress failed"); + result = makeAddress(&address2); + ck_assert_msg(result == SKY_OK, "makeAddress failed"); + + result = SKY_coin_Transaction_PushOutput(*handle, &address1, 1000000, 50); + ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_PushOutput failed"); + result = SKY_coin_Transaction_PushOutput(*handle, &address2, 5000000, 50); + ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_PushOutput failed"); + + GoSlice secKeys = {pseckey, 1, 1}; + result = SKY_coin_Transaction_SignInputs(*handle, secKeys); + ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_SignInputs failed"); + result = SKY_coin_Transaction_UpdateHeader(*handle); + ck_assert_msg(result == SKY_OK, "SKY_coin_Transaction_UpdateHeader failed"); } -coin__Transaction *makeTransaction(Transaction__Handle *handle) +void makeTransaction(Transaction__Handle* handle) { - GoUint32_ result; - *handle = 0; - coin__UxOut uxOut; - memset(&uxOut,0,sizeof(coin__UxOut)); - cipher__SecKey seckey; - result = makeUxOutWithSecret(&uxOut, &seckey); - ck_assert_msg(result == SKY_OK, "makeUxOutWithSecret failed"); - coin__Transaction *rest = makeTransactionFromUxOut(&uxOut, &seckey, handle); - return rest; + GoUint32_ result; + *handle = 0; + coin__UxOut uxOut; + memset(&uxOut, 0, sizeof(coin__UxOut)); + cipher__SecKey seckey; + result = makeUxOutWithSecret(&uxOut, &seckey); + ck_assert_msg(result == SKY_OK, "makeUxOutWithSecret failed"); + makeTransactionFromUxOut(&uxOut, &seckey, handle); } -coin__Transaction *makeEmptyTransaction(Transaction__Handle *handle) +void makeEmptyTransaction(Transaction__Handle* handle) { - GoUint32_ result; - coin__Transaction *ptransaction = NULL; - *handle = 0; - result = SKY_coin_Create_Transaction(handle); - ck_assert_msg(result == SKY_OK, "SKY_coin_Create_Transaction failed"); - result = SKY_coin_GetTransactionObject(*handle, &ptransaction); - ck_assert_msg(result == SKY_OK, "SKY_coin_GetTransactionObject failed"); - return ptransaction; + GoUint32_ result; + coin__Transaction* ptransaction = NULL; + *handle = 0; + result = SKY_coin_Create_Transaction(handle); + ck_assert_msg(result == SKY_OK, "SKY_coin_Create_Transaction failed"); } -GoUint32_ makeTransactions(GoInt32 n, Transactions__Handle *handle) { - GoUint32_ result = SKY_coin_Create_Transactions(handle); - ck_assert(result == SKY_OK); - GoInt32 i; - for (i = 0; i < n; i++) - { - Transaction__Handle thandle = 0 ; - makeTransaction(&thandle); - registerHandleClose(thandle); - result = SKY_coin_Transactions_Add(*handle, thandle); +GoUint32_ makeTransactions(GoInt32 n, Transactions__Handle* handle) +{ + GoUint32_ result = SKY_coin_Create_Transactions(handle); ck_assert(result == SKY_OK); - } - return result; + GoInt32 i; + for (i = 0; i < n; i++) { + Transaction__Handle thandle = 0; + makeTransaction(&thandle); + registerHandleClose(thandle); + result = SKY_coin_Transactions_Add(*handle, thandle); + ck_assert(result == SKY_OK); + } + return result; } typedef struct { - cipher__SHA256 hash; - Transaction__Handle handle; + cipher__SHA256 hash; + Transaction__Handle handle; } TransactionObjectHandle; GoUint32_ sortTransactions(Transactions__Handle txns_handle, - Transactions__Handle *sorted_txns_handle) + Transactions__Handle* sorted_txns_handle) { - GoUint32_ result = SKY_coin_Create_Transactions(sorted_txns_handle); - ck_assert(result == SKY_OK); - registerHandleClose(*sorted_txns_handle); - GoInt n, i, j; - result = SKY_coin_Transactions_Length(txns_handle, &n); - ck_assert(result == SKY_OK); - TransactionObjectHandle *pTrans = malloc(n * sizeof(TransactionObjectHandle)); - ck_assert(pTrans != NULL); - registerMemCleanup(pTrans); - memset(pTrans, 0, n * sizeof(TransactionObjectHandle)); - int *indexes = malloc(n * sizeof(int)); - ck_assert(indexes != NULL); - registerMemCleanup(indexes); - for (i = 0; i < n; i++) - { - indexes[i] = i; - result = SKY_coin_Transactions_GetAt(txns_handle, i, &pTrans[i].handle); + GoUint32_ result = SKY_coin_Create_Transactions(sorted_txns_handle); ck_assert(result == SKY_OK); - registerHandleClose(pTrans[i].handle); - result = SKY_coin_Transaction_Hash(pTrans[i].handle, &pTrans[i].hash); + registerHandleClose(*sorted_txns_handle); + GoInt n, i, j; + result = SKY_coin_Transactions_Length(txns_handle, &n); ck_assert(result == SKY_OK); - } + TransactionObjectHandle* pTrans = malloc(n * sizeof(TransactionObjectHandle)); + ck_assert(pTrans != NULL); + registerMemCleanup(pTrans); + memset(pTrans, 0, n * sizeof(TransactionObjectHandle)); + int* indexes = malloc(n * sizeof(int)); + ck_assert(indexes != NULL); + registerMemCleanup(indexes); + for (i = 0; i < n; i++) { + indexes[i] = i; + result = SKY_coin_Transactions_GetAt(txns_handle, i, &pTrans[i].handle); + ck_assert(result == SKY_OK); + registerHandleClose(pTrans[i].handle); + result = SKY_coin_Transaction_Hash(pTrans[i].handle, &pTrans[i].hash); + ck_assert(result == SKY_OK); + } - // Swap sort. - cipher__SHA256 hash1, hash2; - for (i = 0; i < n - 1; i++) - { - for (j = i + 1; j < n; j++) - { - int cmp = memcmp(&pTrans[indexes[i]].hash, &pTrans[indexes[j]].hash, - sizeof(cipher__SHA256)); - if (cmp > 0) - { - // Swap - int tmp = indexes[i]; - indexes[i] = indexes[j]; - indexes[j] = tmp; - } + // Swap sort. + cipher__SHA256 hash1, hash2; + for (i = 0; i < n - 1; i++) { + for (j = i + 1; j < n; j++) { + int cmp = memcmp(&pTrans[indexes[i]].hash, &pTrans[indexes[j]].hash, sizeof(cipher__SHA256)); + if (cmp > 0) { + // Swap + int tmp = indexes[i]; + indexes[i] = indexes[j]; + indexes[j] = tmp; + } + } } - } - for (i = 0; i < n; i++) - { - result = SKY_coin_Transactions_Add(*sorted_txns_handle, - pTrans[indexes[i]].handle); - ck_assert(result == SKY_OK); - } - return result; + for (i = 0; i < n; i++) { + result = SKY_coin_Transactions_Add(*sorted_txns_handle, pTrans[indexes[i]].handle); + ck_assert(result == SKY_OK); + } + return result; } -coin__Transaction *copyTransaction(Transaction__Handle handle, - Transaction__Handle *handle2) +void copyTransaction(Transaction__Handle handle, + Transaction__Handle* handle2) { - coin__Transaction *ptransaction = NULL; - GoUint32_ result = 0; - result = SKY_coin_Transaction_Copy(handle, handle2); - ck_assert(result == SKY_OK); - registerHandleClose(*handle2); - result = SKY_coin_GetTransactionObject(*handle2, &ptransaction); - registerMemCleanup(ptransaction); - ck_assert_msg(result == SKY_OK, "SKY_coin_GetTransactionObject failed"); - return ptransaction; + GoUint32_ result = 0; + result = SKY_coin_Transaction_Copy(handle, handle2); + ck_assert_int_eq(result, SKY_OK); + registerHandleClose(*handle2); } -void makeRandHash(cipher__SHA256 *phash) +void makeRandHash(cipher__SHA256* phash) { - char buff[1024]; - GoSlice slice = {buff, 0, 1024}; - randBytes(&slice, 128); - registerMemCleanup(slice.data); - GoUint32_ result = SKY_cipher_SumSHA256(slice, phash); - ck_assert_msg(result == SKY_OK, "SKY_cipher_SumSHA256 failed"); + char buff[1024]; + GoSlice slice = {buff, 0, 1024}; + randBytes(&slice, 128); + registerMemCleanup(slice.data); + GoUint32_ result = SKY_cipher_SumSHA256(slice, phash); + ck_assert_msg(result == SKY_OK, "SKY_cipher_SumSHA256 failed"); } -GoUint32_ makeUxArray(coin__UxArray *parray, GoUint32_ n) +GoUint32_ makeUxArray(coin__UxArray* parray, GoUint32_ n) { - parray->data = malloc(sizeof(coin__UxOut) * n); - if (!parray->data) - return SKY_ERROR; - registerMemCleanup(parray->data); - parray->cap = parray->len = n; - coin__UxOut *p = (coin__UxOut *)parray->data; - GoUint32_ result = SKY_OK; - GoUint32_ i; - for (i = 0; i < n; i++) - { - result = makeUxOut(p); - if (result != SKY_OK) - break; - p++; - } - return result; + parray->data = malloc(sizeof(coin__UxOut) * n); + if (!parray->data) + return SKY_ERROR; + registerMemCleanup(parray->data); + parray->cap = parray->len = n; + coin__UxOut* p = (coin__UxOut*)parray->data; + GoUint32_ result = SKY_OK; + GoUint32_ i; + for (i = 0; i < n; i++) { + result = makeUxOut(p); + if (result != SKY_OK) + break; + p++; + } + return result; } diff --git a/lib/cgo/testutil.testutil.go b/lib/cgo/testutil.testutil.go index ce8776849..92d61c903 100644 --- a/lib/cgo/testutil.testutil.go +++ b/lib/cgo/testutil.testutil.go @@ -1,8 +1,13 @@ package main import ( + "crypto/rand" + "reflect" "unsafe" + cipher "github.com/skycoin/skycoin/src/cipher" + "github.com/skycoin/skycoin/src/cipher/bip39" + "github.com/skycoin/skycoin/src/cipher/bip44" testutil "github.com/skycoin/skycoin/src/testutil" ) @@ -21,3 +26,67 @@ func SKY_testutil_MakeAddress(_arg0 *C.cipher__Address) (____error_code uint32) *_arg0 = *(*C.cipher__Address)(unsafe.Pointer(&__arg0)) return } + +//export SKY_testutil_MakePubKey +func SKY_testutil_MakePubKey(_arg0 *C.cipher__PubKey) (____error_code uint32) { + __arg0 := testutil.MakePubKey() + *_arg0 = *(*C.cipher__PubKey)(unsafe.Pointer(&__arg0)) + return +} + +// RandBytes returns n random bytes +func SKY_testutil_RandBytes(n int, _arg0 *C.GoSlice_) (____error_code uint32) { + b := make([]byte, n) + _, err := rand.Read(b) + if err != nil { + ____error_code = SKY_BAD_HANDLE + return + } + copyToGoSlice(reflect.ValueOf(b), _arg0) + return +} + +//export SKY_testutil_RandSHA256 +func SKY_testutil_RandSHA256(_arg0 *C.cipher__SHA256) (____error_code uint32) { + b := make([]byte, 128) + _, err := rand.Read(b) + if err != nil { + ____error_code = SKY_BAD_HANDLE + return + } + arg0 := cipher.SumSHA256(b) + copyToBuffer(reflect.ValueOf(arg0[:]), unsafe.Pointer(_arg0), uint(SizeofSHA256)) + return +} + +//export SKY_testutil_RandXPub +func SKY_testutil_RandXPub(_arg0 *C.PublicKey__Handle) (____error_code uint32) { + m, err := bip39.NewDefaultMnemonic() + ____error_code = libErrorCode(err) + if err != nil { + return + } + s, err := bip39.NewSeed(m, "") + ____error_code = libErrorCode(err) + if err != nil { + return + } + + c, err := bip44.NewCoin(s, bip44.CoinTypeSkycoin) + ____error_code = libErrorCode(err) + if err != nil { + return + } + x, err := c.Account(0) + ____error_code = libErrorCode(err) + if err != nil { + return + } + e, err := x.External() + ____error_code = libErrorCode(err) + if err != nil { + return + } + *_arg0 = registerPublicKeyHandle(e.PublicKey()) + return +} diff --git a/lib/cgo/transaction.hours.go b/lib/cgo/transaction.hours.go index cdad9b0f6..c3043a900 100644 --- a/lib/cgo/transaction.hours.go +++ b/lib/cgo/transaction.hours.go @@ -1,7 +1,6 @@ package main import ( - "reflect" "unsafe" "github.com/skycoin/skycoin/src/transaction" @@ -18,25 +17,25 @@ import ( import "C" //export SKY_transaction_DistributeCoinHoursProportional -func SKY_transaction_DistributeCoinHoursProportional(_coins []uint64, _hours uint64, _arg2 *C.GoSlice_) (____error_code uint32) { +func SKY_transaction_DistributeCoinHoursProportional(_coins []uint64, _hours uint64, _arg2 *[]uint64) (____error_code uint32) { coins := *(*[]uint64)(unsafe.Pointer(&_coins)) hours := _hours __arg2, ____return_err := transaction.DistributeCoinHoursProportional(coins, hours) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg2), _arg2) + *_arg2 = __arg2 } return } //export SKY_transaction_DistributeSpendHours -func SKY_transaction_DistributeSpendHours(_inputHours, _nAddrs uint64, _haveChange bool, _arg2 *uint64, _arg3 *C.GoSlice_, _arg4 *uint64) (____error_code uint32) { +func SKY_transaction_DistributeSpendHours(_inputHours, _nAddrs uint64, _haveChange bool, _arg2 *uint64, _arg3 *[]uint64, _arg4 *uint64) (____error_code uint32) { inputHours := _inputHours nAddrs := _nAddrs haveChange := _haveChange __arg2, __arg3, __arg4 := transaction.DistributeSpendHours(inputHours, nAddrs, haveChange) *_arg2 = __arg2 - copyToGoSlice(reflect.ValueOf(__arg3), _arg3) + *_arg3 = __arg3 *_arg4 = __arg4 return } diff --git a/lib/cgo/util.cert.cert.go b/lib/cgo/util.cert.cert.go index 23943a2f5..82065fa28 100644 --- a/lib/cgo/util.cert.cert.go +++ b/lib/cgo/util.cert.cert.go @@ -1,8 +1,6 @@ package main import ( - "reflect" - cert "github.com/skycoin/skycoin/src/util/certutil" ) @@ -16,13 +14,13 @@ import ( import "C" //export SKY_certutil_NewTLSCertPair -func SKY_certutil_NewTLSCertPair(organization string, validUntil string, extraHosts []string, _cert *C.GoSlice_, _key *C.GoSlice_) (____error_code uint32) { +func SKY_certutil_NewTLSCertPair(organization string, validUntil string, extraHosts []string, _cert *[]byte, _key *[]byte) (____error_code uint32) { ____time_validUntil, ____return_err := parseTimeValue(validUntil) if ____return_err == nil { cert, key, ____return_err := cert.NewTLSCertPair(organization, ____time_validUntil, extraHosts) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(cert), _cert) - copyToGoSlice(reflect.ValueOf(key), _key) + *_cert = cert + *_key = key } } ____error_code = libErrorCode(____return_err) diff --git a/lib/cgo/util.file.file.go b/lib/cgo/util.file.file.go index 5b7d6c295..841deeeef 100644 --- a/lib/cgo/util.file.file.go +++ b/lib/cgo/util.file.file.go @@ -12,40 +12,38 @@ import file "github.com/skycoin/skycoin/src/util/file" import "C" //export SKY_file_InitDataDir -func SKY_file_InitDataDir(_dir string, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_file_InitDataDir(_dir string, _arg1 *string) (____error_code uint32) { dir := _dir __arg1, ____return_err := file.InitDataDir(dir) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg1, _arg1) + *_arg1 = __arg1 } return } //export SKY_file_UserHome -func SKY_file_UserHome(_arg0 *C.GoString_) (____error_code uint32) { - __arg0 := file.UserHome() - copyString(__arg0, _arg0) +func SKY_file_UserHome(_arg0 *string) (____error_code uint32) { + *_arg0 = file.UserHome() return } //export SKY_file_ResolveResourceDirectory -func SKY_file_ResolveResourceDirectory(_path string, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_file_ResolveResourceDirectory(_path string, _arg1 *string) (____error_code uint32) { path := _path - __arg1 := file.ResolveResourceDirectory(path) - copyString(__arg1, _arg1) + *_arg1 = file.ResolveResourceDirectory(path) return } //export SKY_file_DetermineResourcePath -func SKY_file_DetermineResourcePath(_staticDir string, _resourceDir string, _devDir string, _arg3 *C.GoString_) (____error_code uint32) { +func SKY_file_DetermineResourcePath(_staticDir string, _resourceDir string, _devDir string, _arg3 *string) (____error_code uint32) { staticDir := _staticDir resourceDir := _resourceDir devDir := _devDir __arg3, ____return_err := file.DetermineResourcePath(staticDir, resourceDir, devDir) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg3, _arg3) + *_arg3 = __arg3 } return } diff --git a/lib/cgo/util.http.json.go b/lib/cgo/util.http.json.go index d311d1965..2fcc1ce1c 100644 --- a/lib/cgo/util.http.json.go +++ b/lib/cgo/util.http.json.go @@ -1,7 +1,6 @@ package main import ( - "reflect" "unsafe" http "github.com/skycoin/skycoin/src/util/http" @@ -28,12 +27,12 @@ func SKY_httphelper_Address_UnmarshalJSON(_a *C.httphelper__Address, _b []byte) } //export SKY_httphelper_Address_MarshalJSON -func SKY_httphelper_Address_MarshalJSON(_a *C.httphelper__Address, _arg0 *C.GoSlice_) (____error_code uint32) { +func SKY_httphelper_Address_MarshalJSON(_a *C.httphelper__Address, _arg0 *[]byte) (____error_code uint32) { a := *inplaceHttpHelperAddress(_a) __arg0, ____return_err := a.MarshalJSON() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + *_arg0 = __arg0 } return } @@ -50,12 +49,12 @@ func SKY_httphelper_Coins_UnmarshalJSON(_c *C.httphelper__Coins, _b []byte) (___ } //export SKY_httphelper_Coins_MarshalJSON -func SKY_httphelper_Coins_MarshalJSON(_c *C.httphelper__Coins, _arg0 *C.GoSlice_) (____error_code uint32) { +func SKY_httphelper_Coins_MarshalJSON(_c *C.httphelper__Coins, _arg0 *[]byte) (____error_code uint32) { c := *(*http.Coins)(unsafe.Pointer(_c)) __arg0, ____return_err := c.MarshalJSON() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + *_arg0 = __arg0 } return } @@ -80,12 +79,12 @@ func SKY_httphelper_Hours_UnmarshalJSON(_h *C.httphelper__Hours, _b []byte) (___ } //export SKY_httphelper_Hours_MarshalJSON -func SKY_httphelper_Hours_MarshalJSON(_h *C.httphelper__Hours, _arg0 *C.GoSlice_) (____error_code uint32) { +func SKY_httphelper_Hours_MarshalJSON(_h *C.httphelper__Hours, _arg0 *[]byte) (____error_code uint32) { h := *(*http.Hours)(unsafe.Pointer(_h)) __arg0, ____return_err := h.MarshalJSON() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + *_arg0 = __arg0 } return } diff --git a/lib/cgo/util.iputil.iputil.go b/lib/cgo/util.iputil.iputil.go index f3906de38..5d51c8f7d 100644 --- a/lib/cgo/util.iputil.iputil.go +++ b/lib/cgo/util.iputil.iputil.go @@ -12,11 +12,11 @@ import iputil "github.com/skycoin/skycoin/src/util/iputil" import "C" //export SKY_iputil_LocalhostIP -func SKY_iputil_LocalhostIP(_arg0 *C.GoString_) (____error_code uint32) { +func SKY_iputil_LocalhostIP(_arg0 *string) (____error_code uint32) { __arg0, ____return_err := iputil.LocalhostIP() ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg0, _arg0) + *_arg0 = __arg0 } return } @@ -30,12 +30,12 @@ func SKY_iputil_IsLocalhost(_addr string, _arg1 *bool) (____error_code uint32) { } //export SKY_iputil_SplitAddr -func SKY_iputil_SplitAddr(_addr string, _arg1 *C.GoString_, _arg2 *uint16) (____error_code uint32) { +func SKY_iputil_SplitAddr(_addr string, _arg1 *string, _arg2 *uint16) (____error_code uint32) { addr := _addr __arg1, __arg2, ____return_err := iputil.SplitAddr(addr) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(__arg1, _arg1) + *_arg1 = __arg1 *_arg2 = __arg2 } return diff --git a/lib/cgo/wallet.collection_wallet.go b/lib/cgo/wallet.collection_wallet.go new file mode 100644 index 000000000..b5bd77b91 --- /dev/null +++ b/lib/cgo/wallet.collection_wallet.go @@ -0,0 +1,89 @@ +package main + +import ( + "reflect" + "unsafe" + + cipher "github.com/skycoin/skycoin/src/cipher" + wallet "github.com/skycoin/skycoin/src/wallet" +) + +/* + + #include + #include + + #include "skytypes.h" +*/ +import "C" + +//export SKY_wallet_CollectionWallet_AddEntry +func SKY_wallet_CollectionWallet_AddEntry(_w C.CollectionWallet__Handle, _entry *C.wallet__Entry) (____error_code uint32) { + w, okw := lookupCollectionWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + entry := *(*wallet.Entry)(unsafe.Pointer(_entry)) + ____return_err := w.AddEntry(entry) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + } + return +} + +//export SKY_wallet_CollectionWallet_GetEntry +func SKY_wallet_CollectionWallet_GetEntry(_w C.CollectionWallet__Handle, _a *C.cipher__Address, _arg1 *C.wallet__Entry, _arg2 *bool) (____error_code uint32) { + w, okw := lookupCollectionWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + a := *(*cipher.Address)(unsafe.Pointer(_a)) + __arg1, __arg2 := w.GetEntry(a) + *_arg1 = *(*C.wallet__Entry)(unsafe.Pointer(&__arg1)) + *_arg2 = __arg2 + return +} + +//export SKY_wallet_CollectionWallet_GetAddresses +func SKY_wallet_CollectionWallet_GetAddresses(_w C.CollectionWallet__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { + w, okw := lookupCollectionWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + __arg0 := w.GetAddresses() + copyToGoSlice(reflect.ValueOf(__arg0), _arg0) + return +} + +//export SKY_wallet_CollectionWallet_GenerateAddresses +func SKY_wallet_CollectionWallet_GenerateAddresses(_w C.CollectionWallet__Handle, _num uint64, _arg1 *C.GoSlice_) (____error_code uint32) { + w, okw := lookupCollectionWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + num := _num + __arg1, ____return_err := w.GenerateAddresses(num) + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + copyToGoSlice(reflect.ValueOf(__arg1), _arg1) + } + return +} + +//export SKY_wallet_CollectionWallet_Validate +func SKY_wallet_CollectionWallet_Validate(_w C.CollectionWallet__Handle) (____error_code uint32) { + w, okw := lookupCollectionWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + ____return_err := w.Validate() + ____error_code = libErrorCode(____return_err) + if ____return_err == nil { + } + return +} diff --git a/lib/cgo/wallet.crypto.go b/lib/cgo/wallet.crypto.go index 86a9bc146..84dc012f2 100644 --- a/lib/cgo/wallet.crypto.go +++ b/lib/cgo/wallet.crypto.go @@ -1,6 +1,8 @@ package main import ( + "unsafe" + wallet "github.com/skycoin/skycoin/src/wallet" ) @@ -14,12 +16,12 @@ import ( import "C" //export SKY_wallet_CryptoTypeFromString -func SKY_wallet_CryptoTypeFromString(_s string, _arg1 *C.GoString_) (____error_code uint32) { +func SKY_wallet_CryptoTypeFromString(_s string, _arg1 *C.wallet__CryptoType) (____error_code uint32) { s := _s __arg1, ____return_err := wallet.CryptoTypeFromString(s) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - copyString(string(__arg1), _arg1) + *_arg1 = *(*C.wallet__CryptoType)(unsafe.Pointer(&__arg1)) } return } diff --git a/lib/cgo/wallet.meta.go b/lib/cgo/wallet.meta.go new file mode 100644 index 000000000..7dca73a95 --- /dev/null +++ b/lib/cgo/wallet.meta.go @@ -0,0 +1,67 @@ +package main + +/* + + #include + #include + + #include "skytypes.h" +*/ +import "C" + +//export SKY_wallet_MetaWallet_IsEncrypted +func SKY_wallet_MetaWallet_IsEncrypted(_w C.MetaWallet__Handle, _arg0 *bool) (____error_code uint32) { + w, okw := lookupMetaWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + __arg0 := w.IsEncrypted() + *_arg0 = __arg0 + return +} + +//export SKY_wallet_MetaWallet_Label +func SKY_wallet_MetaWallet_Label(_w C.MetaWallet__Handle, _arg0 *string) (____error_code uint32) { + w, okw := lookupMetaWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = w.Label() + return +} + +//export SKY_wallet_MetaWallet_Filename +func SKY_wallet_MetaWallet_Filename(_w C.MetaWallet__Handle, _arg0 *string) (____error_code uint32) { + w, okw := lookupMetaWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = w.Filename() + return +} + +//export SKY_wallet_MetaWallet_Version +func SKY_wallet_MetaWallet_Version(_w C.MetaWallet__Handle, _arg0 *string) (____error_code uint32) { + w, okw := lookupMetaWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = w.Version() + + return +} + +//export SKY_wallet_MetaWallet_Type +func SKY_wallet_MetaWallet_Type(_w C.MetaWallet__Handle, _arg0 *string) (____error_code uint32) { + w, okw := lookupMetaWalletHandle(_w) + if !okw { + ____error_code = SKY_BAD_HANDLE + return + } + *_arg0 = w.Type() + return +} diff --git a/lib/cgo/wallet.readable.go b/lib/cgo/wallet.readable.go index 0747bda66..6c5eed89a 100644 --- a/lib/cgo/wallet.readable.go +++ b/lib/cgo/wallet.readable.go @@ -16,62 +16,10 @@ import ( import "C" //export SKY_wallet_NewReadableEntry -func SKY_wallet_NewReadableEntry(_coinType string, _w *C.wallet__Entry, _arg1 *C.ReadableEntry__Handle) (____error_code uint32) { +func SKY_wallet_NewReadableEntry(_coinType string, _walletType string, _w *C.wallet__Entry, _arg1 *C.ReadableEntry__Handle) (____error_code uint32) { coinType := wallet.CoinType(_coinType) w := *(*wallet.Entry)(unsafe.Pointer(_w)) - __arg1 := wallet.NewReadableEntry(coinType, w) + __arg1 := wallet.NewReadableEntry(coinType, _walletType, w) *_arg1 = registerReadableEntryHandle(&__arg1) return } - -//export SKY_wallet_LoadReadableWallet -func SKY_wallet_LoadReadableWallet(_filename string, _arg1 *C.ReadableWallet__Handle) (____error_code uint32) { - filename := _filename - __arg1, ____return_err := wallet.LoadReadableWallet(filename) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - *_arg1 = registerReadableWalletHandle(__arg1) - } - return -} - -//export SKY_wallet_ReadableWallet_Save -func SKY_wallet_ReadableWallet_Save(_rw C.ReadableWallet__Handle, _filename string) (____error_code uint32) { - rw, okrw := lookupReadableWalletHandle(_rw) - if !okrw { - ____error_code = SKY_BAD_HANDLE - return - } - filename := _filename - ____return_err := rw.Save(filename) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - } - return -} - -//export SKY_wallet_ReadableWallet_Load -func SKY_wallet_ReadableWallet_Load(_rw C.ReadableWallet__Handle, _filename string) (____error_code uint32) { - rw, okrw := lookupReadableWalletHandle(_rw) - if !okrw { - ____error_code = SKY_BAD_HANDLE - return - } - filename := _filename - ____return_err := rw.Load(filename) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - } - return -} - -//export SKY_wallet_ReadableWallet_Erase -func SKY_wallet_ReadableWallet_Erase(_rw C.ReadableWallet__Handle) (____error_code uint32) { - rw, okrw := lookupReadableWalletHandle(_rw) - if !okrw { - ____error_code = SKY_BAD_HANDLE - return - } - rw.Erase() - return -} diff --git a/lib/cgo/wallet.wallet.go b/lib/cgo/wallet.wallet.go index f15c39788..0cd3ec751 100644 --- a/lib/cgo/wallet.wallet.go +++ b/lib/cgo/wallet.wallet.go @@ -1,10 +1,8 @@ package main import ( - "reflect" "unsafe" - cipher "github.com/skycoin/skycoin/src/cipher" wallet "github.com/skycoin/skycoin/src/wallet" ) @@ -38,13 +36,13 @@ func SKY_wallet_NewWallet(_wltName string, _opts C.Options__Handle, _arg2 *C.Wal __arg2, ____return_err := wallet.NewWallet(_wltName, opts) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - *_arg2 = registerWalletHandle(__arg2) + *_arg2 = registerWalletHandle(&__arg2) } return } -//export SKY_wallet_Wallet_Lock -func SKY_wallet_Wallet_Lock(_w C.Wallet__Handle, _password []byte, _cryptoType string) (____error_code uint32) { +//export SKY_wallet_Lock +func SKY_wallet_Lock(_w C.Wallet__Handle, _password []byte, _cryptoType string) (____error_code uint32) { w, okw := lookupWalletHandle(_w) if !okw { ____error_code = SKY_BAD_HANDLE @@ -52,25 +50,25 @@ func SKY_wallet_Wallet_Lock(_w C.Wallet__Handle, _password []byte, _cryptoType s } password := *(*[]byte)(unsafe.Pointer(&_password)) cryptoType := wallet.CryptoType(_cryptoType) - ____return_err := w.Lock(password, cryptoType) + ____return_err := wallet.Lock(*w, password, cryptoType) ____error_code = libErrorCode(____return_err) if ____return_err == nil { } return } -//export SKY_wallet_Wallet_Unlock -func SKY_wallet_Wallet_Unlock(_w C.Wallet__Handle, _password []byte, _arg1 *C.Wallet__Handle) (____error_code uint32) { +//export SKY_wallet_Unlock +func SKY_wallet_Unlock(_w C.Wallet__Handle, _password []byte, _arg1 *C.Wallet__Handle) (____error_code uint32) { w, okw := lookupWalletHandle(_w) if !okw { ____error_code = SKY_BAD_HANDLE return } password := *(*[]byte)(unsafe.Pointer(&_password)) - __arg1, ____return_err := w.Unlock(password) + __arg1, ____return_err := wallet.Unlock(*w, password) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - *_arg1 = registerWalletHandle(__arg1) + *_arg1 = registerWalletHandle(&__arg1) } return } @@ -81,7 +79,7 @@ func SKY_wallet_Load(_wltFile string, _arg1 *C.Wallet__Handle) (____error_code u __arg1, ____return_err := wallet.Load(wltFile) ____error_code = libErrorCode(____return_err) if ____return_err == nil { - *_arg1 = registerWalletHandle(__arg1) + *_arg1 = registerWalletHandle(&__arg1) } return } @@ -94,138 +92,7 @@ func SKY_wallet_Wallet_Save(_w C.Wallet__Handle, _dir string) (____error_code ui return } dir := _dir - ____return_err := w.Save(dir) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - } - return -} - -//export SKY_wallet_Wallet_Validate -func SKY_wallet_Wallet_Validate(_w C.Wallet__Handle) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - ____return_err := w.Validate() - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - } - return -} - -//export SKY_wallet_Wallet_Type -func SKY_wallet_Wallet_Type(_w C.Wallet__Handle, _arg0 *C.GoString_) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - __arg0 := w.Type() - copyString(__arg0, _arg0) - return -} - -//export SKY_wallet_Wallet_Version -func SKY_wallet_Wallet_Version(_w C.Wallet__Handle, _arg0 *C.GoString_) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - __arg0 := w.Version() - copyString(__arg0, _arg0) - return -} - -//export SKY_wallet_Wallet_Filename -func SKY_wallet_Wallet_Filename(_w C.Wallet__Handle, _arg0 *C.GoString_) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - __arg0 := w.Filename() - copyString(__arg0, _arg0) - return -} - -//export SKY_wallet_Wallet_Label -func SKY_wallet_Wallet_Label(_w C.Wallet__Handle, _arg0 *C.GoString_) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - __arg0 := w.Label() - copyString(__arg0, _arg0) - return -} - -//export SKY_wallet_Wallet_IsEncrypted -func SKY_wallet_Wallet_IsEncrypted(_w C.Wallet__Handle, _arg0 *bool) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - __arg0 := w.IsEncrypted() - *_arg0 = __arg0 - return -} - -//export SKY_wallet_Wallet_GenerateAddresses -func SKY_wallet_Wallet_GenerateAddresses(_w C.Wallet__Handle, _num uint64, _arg1 *C.GoSlice_) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - num := _num - __arg1, ____return_err := w.GenerateAddresses(num) - ____error_code = libErrorCode(____return_err) - if ____return_err == nil { - copyToGoSlice(reflect.ValueOf(__arg1), _arg1) - } - return -} - -//export SKY_wallet_Wallet_GetAddresses -func SKY_wallet_Wallet_GetAddresses(_w C.Wallet__Handle, _arg0 *C.GoSlice_) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - __arg0 := w.GetAddresses() - copyToGoSlice(reflect.ValueOf(__arg0), _arg0) - return -} - -//export SKY_wallet_Wallet_GetEntry -func SKY_wallet_Wallet_GetEntry(_w C.Wallet__Handle, _a *C.cipher__Address, _arg1 *C.wallet__Entry, _arg2 *bool) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - a := *(*cipher.Address)(unsafe.Pointer(_a)) - __arg1, __arg2 := w.GetEntry(a) - *_arg1 = *(*C.wallet__Entry)(unsafe.Pointer(&__arg1)) - *_arg2 = __arg2 - return -} - -//export SKY_wallet_Wallet_AddEntry -func SKY_wallet_Wallet_AddEntry(_w C.Wallet__Handle, _entry *C.wallet__Entry) (____error_code uint32) { - w, okw := lookupWalletHandle(_w) - if !okw { - ____error_code = SKY_BAD_HANDLE - return - } - entry := *(*wallet.Entry)(unsafe.Pointer(_entry)) - ____return_err := w.AddEntry(entry) + ____return_err := wallet.Save(*w, dir) ____error_code = libErrorCode(____return_err) if ____return_err == nil { } diff --git a/lib/swig/dynamic/golang.cgo.i b/lib/swig/dynamic/golang.cgo.i index edd10219e..c6411f681 100644 --- a/lib/swig/dynamic/golang.cgo.i +++ b/lib/swig/dynamic/golang.cgo.i @@ -69,7 +69,29 @@ /*GoUint64* as function return typemap*/ %typemap(argout) GoUint64* { - %append_output( SWIG_From_long( *$1 ) ); + %append_output( SWIG_From_unsigned_SS_long_SS_long( *$1 ) ); +} + +/*GoUint32* parameter as reference */ +%typemap(in, numinputs=0) GoUint32* (GoUint32 temp) { + temp = 0; + $1 = &temp; +} + +/*GoUint32* as function return typemap*/ +%typemap(argout) GoUint32* { + %append_output( SWIG_From_unsigned_SS_int( *$1 ) ); +} + +/*GoUint8* parameter as reference */ +%typemap(in, numinputs=0) GoUint8* (GoUint8 temp) { + temp = 0; + $1 = &temp; +} + +/*GoUint8* as function return typemap*/ +%typemap(argout) GoUint8* { + %append_output( SWIG_From_unsigned_SS_char( *$1 ) ); } /*GoInt64* parameter as reference */ diff --git a/lib/swig/dynamic/mem.i b/lib/swig/dynamic/mem.i index 03c68d100..01572a325 100644 --- a/lib/swig/dynamic/mem.i +++ b/lib/swig/dynamic/mem.i @@ -25,7 +25,7 @@ GoStringMap, PasswordReader__Handle_, Transaction__Handle, Transactions__Handle, CreatedTransaction__Handle, CreatedTransactionOutput__Handle, CreatedTransactionInput__Handle, CreateTransactionResponse__Handle, - Block__Handle, SignedBlock__Handle, BlockBody__Handle, BuildInfo_Handle, Number_Handle, Signature_Handle,AddressUxOuts_Handle + Block__Handle, SignedBlock__Handle, BlockBody__Handle, BuildInfo_Handle, Number_Handle, Signature_Handle,AddressUxOuts_Handle,Distribution__Handle } %apply Handle* { Wallet__Handle*, Options__Handle*, ReadableEntry__Handle*, ReadableWallet__Handle*, WebRpcClient__Handle*, @@ -33,5 +33,5 @@ CLI__Handle*, Context__Handle*, GoStringMap_*, PasswordReader__Handle*, Transaction__Handle*, Transactions__Handle*, CreatedTransaction__Handle*, CreatedTransactionOutput__Handle*, CreatedTransactionInput__Handle*, CreateTransactionResponse__Handle*, - Block__Handle*, SignedBlock__Handle*, BlockBody__Handle*, BuildInfo_Handle*, Number_Handle*, Signature_Handle*,AddressUxOuts_Handle* + Block__Handle*, SignedBlock__Handle*, BlockBody__Handle*, BuildInfo_Handle*, Number_Handle*, Signature_Handle*,AddressUxOuts_Handle*,Distribution__Handle* } \ No newline at end of file diff --git a/lib/swig/dynamic/typemaps.i b/lib/swig/dynamic/typemaps.i index 3334228e9..444b4bb64 100644 --- a/lib/swig/dynamic/typemaps.i +++ b/lib/swig/dynamic/typemaps.i @@ -8,6 +8,16 @@ %append_output( SWIG_From_unsigned_SS_long_SS_long( *$1 ) ); } +/*GoUint32* as function return typemap*/ +%typemap(argout) GoUint32* { + %append_output( SWIG_From_unsigned_SS_int( *$1 ) ); +} + +/*GoUint8* as function return typemap*/ +%typemap(argout) GoUint8* { + %append_output( SWIG_From_unsigned_SS_char( *$1 ) ); +} + /* cipher__PubKey* input typemap */ @@ -73,9 +83,8 @@ cipher__SecKey* input typemap %apply int* OUTPUT {GoInt*} %apply int* OUTPUT {GoUint*} -%apply int* OUTPUT {GoUint8*} +// %apply int* OUTPUT {GoUint8*} %apply int* OUTPUT {GoInt8*} %apply int* OUTPUT {GoUint16*} %apply int* OUTPUT {GoInt16*} -%apply int* OUTPUT {GoUint32*} %apply int* OUTPUT {GoInt32*} diff --git a/vendor/github.com/skycoin/skycoin b/vendor/github.com/skycoin/skycoin index ff754084d..7d49e9b0c 160000 --- a/vendor/github.com/skycoin/skycoin +++ b/vendor/github.com/skycoin/skycoin @@ -1 +1 @@ -Subproject commit ff754084df0912bc0d151529e2893ca86618fb3f +Subproject commit 7d49e9b0c4110a587c9670c513dfd1a0fa72004c