def test2of3MultiSigTx(self): tx1 = PyTx().unserialize(hex_to_binary('010000000371c06e0639dbe6bc35e6f948da4874ae69d9d91934ec7c5366292d0cbd5f97b0010000008a47304402200117cdd3ec6259af29acea44db354a6f57ac10d8496782033f5fe0febfd77f1b02202ceb02d60dbb43e6d4e03e5b5fbadc031f8bbb3c6c34ad307939947987f600bf01410452d63c092209529ca2c75e056e947bc95f9daffb371e601b46d24377aaa3d004ab3c6be2d6d262b34d736b95f3b0ef6876826c93c4077d619c02ebd974c7facdffffffffa65aa866aa7743ec05ba61418015fc32ecabd99886732056f1d4454c8f762bf8000000008c493046022100ea0a9b41c9372837e52898205c7bebf86b28936a3ee725672d0ca8f434f876f0022100beb7243a51fbc0997e55cb519d3b9cbd59f7aba68d80ba1e8adbb53443cda3c00141043efd1ca3cffc50638031281d227ff347a3a27bc145e2f846891d29f87bc068c27710559c4d9cd71f7e9e763d6e2753172406eb1ed1fadcaf9a8972b4270f05b4ffffffffd866d14151ee1b733a2a7273f155ecb25c18303c31b2c4de5aa6080aef2e0006000000008b483045022052210f95f6b413c74ce12cfc1b14a36cb267f9fa3919fa6e20dade1cd570439f022100b9e5b325f312904804f043d06c6ebc8e4b1c6cd272856c48ab1736b9d562e10c01410423fdddfe7e4d70d762dd6596771e035f4b43d54d28c2231be1102056f81f067914fe4fb6fd6e3381228ee5587ddd2028c846025741e963d9b1d6cf2c2dea0dbcffffffff0210ef3200000000004341048a33e9fd2de28137574cc69fe5620199abe37b7d08a51c528876fe6c5fa7fc28535f5a667244445e79fffc9df85ec3d79d77693b1f37af0e2d7c1fa2e7113a48acc0d454070000000061526b006b7dac7ca9143cd1def404e12a85ead2b4d3f5f9f817fb0d46ef879a6c936b7dac7ca9146a4e7d5f798e90e84db9244d4805459f87275943879a6c936b7dac7ca914486efdd300987a054510b4ce1148d4ad290d911e879a6c936b6c6ca200000000')) tx2 = PyTx().unserialize(hex_to_binary('01000000012f654d4d1d7246d1a824c5b6c5177c0b5a1983864579aabb88cabd5d05e032e201000000fda0014730440220151ad44e7f78f9e0c4a3f2135c19ca3de8dbbb7c58893db096c0c5f1573d5dec02200724a78c3fa5f153103cb46816df46eb6cfac3718038607ddec344310066161e01410459fd82189b81772258a3fc723fdda900eb8193057d4a573ee5ad39e26b58b5c12c4a51b0edd01769f96ed1998221daf0df89634a7137a8fa312d5ccc95ed8925483045022100ca34834ece5925cff6c3d63e2bda6b0ce0685b18f481c32e70de9a971e85f12f0220572d0b5de0cf7b8d4e28f4914a955e301faaaa42f05feaa1cc63b45f938d75d9014104ce6242d72ee67e867e6f8ec434b95fcb1889c5b485ec3414df407e11194a7ce012eda021b68f1dd124598a9b677d6e7d7c95b1b7347f5c5a08efa628ef0204e1483045022074e01e8225e8c4f9d0b3f86908d42a61e611f406e13817d16240f94f52f49359022100f4c768dd89c6435afd3834ae2c882465ade92d7e1cc5c2c2c3d8d25c41b3ea61014104ce66c9f5068b715b62cc1622572cd98a08812d8ca01563045263c3e7af6b997e603e8e62041c4eb82dfd386a3412c34c334c34eb3c76fb0e37483fc72323f807ffffffff01b0ad5407000000001976a9146a4e7d5f798e90e84db9244d4805459f8727594388ac00000000')) # Verify 2-of-3 tx from Testnet psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def test2of2MultiSigTx(self): tx1 = PyTx().unserialize(hex_to_binary('010000000189a0022c8291b4328338ec95179612b8ebf72067051de019a6084fb97eae0ebe000000004a4930460221009627882154854e3de066943ba96faba02bb8b80c1670a0a30d0408caa49f03df022100b625414510a2a66ebb43fffa3f4023744695380847ee1073117ec90cb60f2c8301ffffffff0210c18d0000000000434104a701496f10db6aa8acbb6a7aa14d62f4925f8da03de7f0262010025945f6ebcc3efd55b6aa4bc6f811a0dc1bbdd2644bdd81c8a63766aa11f650cd7736bbcaf8ac001bb7000000000043526b006b7dac7ca914fc1243972b59c1726735d3c5cca40e415039dce9879a6c936b7dac7ca914375dd72e03e7b5dbb49f7e843b7bef4a2cc2ce9e879a6c936b6c6ca200000000')) tx2 = PyTx().unserialize(hex_to_binary('01000000011c9608650a912be7fa88eecec664e6fbfa4b676708697fa99c28b3370005f32d01000000fd1701483045022017462c29efc9158cf26f2070d444bb2b087b8a0e6287a9274fa36fad30c46485022100c6d4cc6cd504f768389637df71c1ccd452e0691348d0f418130c31da8cc2a6e8014104e83c1d4079a1b36417f0544063eadbc44833a992b9667ab29b4ff252d8287687bad7581581ae385854d4e5f1fcedce7de12b1aec1cb004cabb2ec1f3de9b2e60493046022100fdc7beb27de0c3a53fbf96df7ccf9518c5fe7873eeed413ce17e4c0e8bf9c06e022100cc15103b3c2e1f49d066897fe681a12e397e87ed7ee39f1c8c4a5fef30f4c2c60141047cf315904fcc2e3e2465153d39019e0d66a8aaec1cec1178feb10d46537427239fd64b81e41651e89b89fefe6a23561d25dddc835395dd3542f83b32a1906aebffffffff01c0d8a700000000001976a914fc1243972b59c1726735d3c5cca40e415039dce988ac00000000')) # Verify 2-of-2 tx from Testnet psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def buildCorruptWallet(self, walletPath): from armoryengine.PyBtcWallet import PyBtcWallet crpWlt = PyBtcWallet() crpWlt.createNewWallet(walletPath, securePassphrase='testing', doRegisterWithBDM=False) #not registering with the BDM, have to fill the wallet address pool manually crpWlt.fillAddressPool(100) #grab the last computed address lastaddr = crpWlt.addrMap[crpWlt.lastComputedChainAddr160] #corrupt the pubkey PubKey = hex_to_binary('0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455') lastaddr.binPublicKey65 = SecureBinaryData(PubKey) crpWlt.addrMap[crpWlt.lastComputedChainAddr160] = lastaddr crpWlt.fillAddressPool(200) #insert a gap and inconsistent encryption newAddr = PyBtcAddress() newAddr.chaincode = lastaddr.chaincode newAddr.chainIndex = 250 PrivKey = hex_to_binary('e3b0c44298fc1c149afbf4c8996fb92427ae41e5978fe51ca495991b7852b855') newAddr.binPrivKey32_Plain = SecureBinaryData(PrivKey) newAddr.binPublicKey65 = CryptoECDSA().ComputePublicKey(newAddr.binPrivKey32_Plain) newAddr.addrStr20 = newAddr.binPublicKey65.getHash160() newAddr.isInitialized = True crpWlt.addrMap[newAddr.addrStr20] = newAddr crpWlt.lastComputedChainAddr160 = newAddr.addrStr20 crpWlt.fillAddressPool(250) #TODO: corrupt a private key #break an address entry at binary level return crpWlt.uniqueIDB58
def testMultiSig(self): tx1 = PyTx().unserialize(hex_to_binary('0100000001845ad165bdc0f9b5829cf5a594c4148dfd89e24756303f3a8dabeb597afa589b010000008b483045022063c233df8efa3d1885e069e375a8eabf16b23475ef21bdc9628a513ee4caceb702210090a102c7b602043e72b34a154d495ac19b3b9e42acb962c399451f2baead8f4c014104b38f79037ad25b84a564eaf53ede93dec70b35216e6682aa71a47cefa2996ec49acfbb0a8730577c62ef9a7cc20c740aaaaee75419bef9640a4216c2b49c42d3ffffffff02000c022900000000434104c08c0a71ccbe838403e3870aa1ab871b0ab3a6014b0ba41f6df2b9aefea73134ecaa0b27797620e402a33799e9047f86519d9e43bbd504cf753c293752933f4fac406f40010000000062537a7652a269537a829178a91480677c5392220db736455533477d0bc2fba65502879b69537a829178a91402d7aa2e76d9066fb2b3c41ff8839a5c81bdca19879b69537a829178a91410039ce4fdb5d4ee56148fe3935b9bfbbe4ecc89879b6953ae00000000')) tx2 = PyTx().unserialize(hex_to_binary('0100000001bb664ff716b9dfc831bcc666c1767f362ad467fcfbaf4961de92e45547daab8701000000fd190100493046022100d73f633f114e0e0b324d87d38d34f22966a03b072803afa99c9408201f6d6dc6022100900e85be52ad2278d24e7edbb7269367f5f2d6f1bd338d017ca460008776614401473044022071fef8ac0aa6318817dbd242bf51fb5b75be312aa31ecb44a0afe7b49fcf840302204c223179a383bb6fcb80312ac66e473345065f7d9136f9662d867acf96c12a42015241048c006ff0d2cfde86455086af5a25b88c2b81858aab67f6a3132c885a2cb9ec38e700576fd46c7d72d7d22555eee3a14e2876c643cd70b1b0a77fbf46e62331ac4104b68ef7d8f24d45e1771101e269c0aacf8d3ed7ebe12b65521712bba768ef53e1e84fff3afbee360acea0d1f461c013557f71d426ac17a293c5eebf06e468253e00ffffffff0280969800000000001976a9140817482d2e97e4be877efe59f4bae108564549f188ac7015a7000000000062537a7652a269537a829178a91480677c5392220db736455533477d0bc2fba65502879b69537a829178a91402d7aa2e76d9066fb2b3c41ff8839a5c81bdca19879b69537a829178a91410039ce4fdb5d4ee56148fe3935b9bfbbe4ecc89879b6953ae00000000')) # OP_CHECKMULTISIG from Testnet psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def extractSignedDataFromVersionsDotTxt(wholeFile, doVerify=True): """ This method returns a pair: a dictionary to lookup link by OS, and a formatted string that is sorted by OS, and re-formatted list that will hash the same regardless of original format or ordering """ msgBegin = wholeFile.find('# -----BEGIN-SIGNED-DATA-') msgBegin = wholeFile.find('\n', msgBegin+1) + 1 msgEnd = wholeFile.find('# -----SIGNATURE---------') sigBegin = wholeFile.find('\n', msgEnd+1) + 3 sigEnd = wholeFile.find('# -----END-SIGNED-DATA---') MSGRAW = wholeFile[msgBegin:msgEnd] SIGHEX = wholeFile[sigBegin:sigEnd].strip() if -1 in [msgBegin,msgEnd,sigBegin,sigEnd]: LOGERROR('No signed data block found') return '' if doVerify: Pub = SecureBinaryData(hex_to_binary(ARMORY_INFO_SIGN_PUBLICKEY)) Msg = SecureBinaryData(MSGRAW) Sig = SecureBinaryData(hex_to_binary(SIGHEX)) isVerified = CryptoECDSA().VerifyData(Msg, Sig, Pub) if not isVerified: LOGERROR('Signed data block failed verification!') return '' else: LOGINFO('Signature on signed data block is GOOD!') return MSGRAW
def extractSignedDataFromVersionsDotTxt(wholeFile, doVerify=True): """ This method returns a pair: a dictionary to lookup link by OS, and a formatted string that is sorted by OS, and re-formatted list that will hash the same regardless of original format or ordering """ msgBegin = wholeFile.find('# -----BEGIN-SIGNED-DATA-') msgBegin = wholeFile.find('\n', msgBegin + 1) + 1 msgEnd = wholeFile.find('# -----SIGNATURE---------') sigBegin = wholeFile.find('\n', msgEnd + 1) + 3 sigEnd = wholeFile.find('# -----END-SIGNED-DATA---') MSGRAW = wholeFile[msgBegin:msgEnd] SIGHEX = wholeFile[sigBegin:sigEnd].strip() if -1 in [msgBegin, msgEnd, sigBegin, sigEnd]: LOGERROR('No signed data block found') return '' if doVerify: Pub = SecureBinaryData(hex_to_binary(ARMORY_INFO_SIGN_PUBLICKEY)) Msg = SecureBinaryData(MSGRAW) Sig = SecureBinaryData(hex_to_binary(SIGHEX)) isVerified = CryptoECDSA().VerifyData(Msg, Sig, Pub) if not isVerified: LOGERROR('Signed data block failed verification!') return '' else: LOGINFO('Signature on signed data block is GOOD!') return MSGRAW
def testMultiSig(self): tx1 = PyTx().unserialize( hex_to_binary( '0100000001845ad165bdc0f9b5829cf5a594c4148dfd89e24756303f3a8dabeb597afa589b010000008b483045022063c233df8efa3d1885e069e375a8eabf16b23475ef21bdc9628a513ee4caceb702210090a102c7b602043e72b34a154d495ac19b3b9e42acb962c399451f2baead8f4c014104b38f79037ad25b84a564eaf53ede93dec70b35216e6682aa71a47cefa2996ec49acfbb0a8730577c62ef9a7cc20c740aaaaee75419bef9640a4216c2b49c42d3ffffffff02000c022900000000434104c08c0a71ccbe838403e3870aa1ab871b0ab3a6014b0ba41f6df2b9aefea73134ecaa0b27797620e402a33799e9047f86519d9e43bbd504cf753c293752933f4fac406f40010000000062537a7652a269537a829178a91480677c5392220db736455533477d0bc2fba65502879b69537a829178a91402d7aa2e76d9066fb2b3c41ff8839a5c81bdca19879b69537a829178a91410039ce4fdb5d4ee56148fe3935b9bfbbe4ecc89879b6953ae00000000' )) tx2 = PyTx().unserialize( hex_to_binary( '0100000001bb664ff716b9dfc831bcc666c1767f362ad467fcfbaf4961de92e45547daab8701000000fd190100493046022100d73f633f114e0e0b324d87d38d34f22966a03b072803afa99c9408201f6d6dc6022100900e85be52ad2278d24e7edbb7269367f5f2d6f1bd338d017ca460008776614401473044022071fef8ac0aa6318817dbd242bf51fb5b75be312aa31ecb44a0afe7b49fcf840302204c223179a383bb6fcb80312ac66e473345065f7d9136f9662d867acf96c12a42015241048c006ff0d2cfde86455086af5a25b88c2b81858aab67f6a3132c885a2cb9ec38e700576fd46c7d72d7d22555eee3a14e2876c643cd70b1b0a77fbf46e62331ac4104b68ef7d8f24d45e1771101e269c0aacf8d3ed7ebe12b65521712bba768ef53e1e84fff3afbee360acea0d1f461c013557f71d426ac17a293c5eebf06e468253e00ffffffff0280969800000000001976a9140817482d2e97e4be877efe59f4bae108564549f188ac7015a7000000000062537a7652a269537a829178a91480677c5392220db736455533477d0bc2fba65502879b69537a829178a91402d7aa2e76d9066fb2b3c41ff8839a5c81bdca19879b69537a829178a91410039ce4fdb5d4ee56148fe3935b9bfbbe4ecc89879b6953ae00000000' )) # OP_CHECKMULTISIG from Testnet psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def test2of3MultiSigTx(self): tx1 = PyTx().unserialize( hex_to_binary( '010000000371c06e0639dbe6bc35e6f948da4874ae69d9d91934ec7c5366292d0cbd5f97b0010000008a47304402200117cdd3ec6259af29acea44db354a6f57ac10d8496782033f5fe0febfd77f1b02202ceb02d60dbb43e6d4e03e5b5fbadc031f8bbb3c6c34ad307939947987f600bf01410452d63c092209529ca2c75e056e947bc95f9daffb371e601b46d24377aaa3d004ab3c6be2d6d262b34d736b95f3b0ef6876826c93c4077d619c02ebd974c7facdffffffffa65aa866aa7743ec05ba61418015fc32ecabd99886732056f1d4454c8f762bf8000000008c493046022100ea0a9b41c9372837e52898205c7bebf86b28936a3ee725672d0ca8f434f876f0022100beb7243a51fbc0997e55cb519d3b9cbd59f7aba68d80ba1e8adbb53443cda3c00141043efd1ca3cffc50638031281d227ff347a3a27bc145e2f846891d29f87bc068c27710559c4d9cd71f7e9e763d6e2753172406eb1ed1fadcaf9a8972b4270f05b4ffffffffd866d14151ee1b733a2a7273f155ecb25c18303c31b2c4de5aa6080aef2e0006000000008b483045022052210f95f6b413c74ce12cfc1b14a36cb267f9fa3919fa6e20dade1cd570439f022100b9e5b325f312904804f043d06c6ebc8e4b1c6cd272856c48ab1736b9d562e10c01410423fdddfe7e4d70d762dd6596771e035f4b43d54d28c2231be1102056f81f067914fe4fb6fd6e3381228ee5587ddd2028c846025741e963d9b1d6cf2c2dea0dbcffffffff0210ef3200000000004341048a33e9fd2de28137574cc69fe5620199abe37b7d08a51c528876fe6c5fa7fc28535f5a667244445e79fffc9df85ec3d79d77693b1f37af0e2d7c1fa2e7113a48acc0d454070000000061526b006b7dac7ca9143cd1def404e12a85ead2b4d3f5f9f817fb0d46ef879a6c936b7dac7ca9146a4e7d5f798e90e84db9244d4805459f87275943879a6c936b7dac7ca914486efdd300987a054510b4ce1148d4ad290d911e879a6c936b6c6ca200000000' )) tx2 = PyTx().unserialize( hex_to_binary( '01000000012f654d4d1d7246d1a824c5b6c5177c0b5a1983864579aabb88cabd5d05e032e201000000fda0014730440220151ad44e7f78f9e0c4a3f2135c19ca3de8dbbb7c58893db096c0c5f1573d5dec02200724a78c3fa5f153103cb46816df46eb6cfac3718038607ddec344310066161e01410459fd82189b81772258a3fc723fdda900eb8193057d4a573ee5ad39e26b58b5c12c4a51b0edd01769f96ed1998221daf0df89634a7137a8fa312d5ccc95ed8925483045022100ca34834ece5925cff6c3d63e2bda6b0ce0685b18f481c32e70de9a971e85f12f0220572d0b5de0cf7b8d4e28f4914a955e301faaaa42f05feaa1cc63b45f938d75d9014104ce6242d72ee67e867e6f8ec434b95fcb1889c5b485ec3414df407e11194a7ce012eda021b68f1dd124598a9b677d6e7d7c95b1b7347f5c5a08efa628ef0204e1483045022074e01e8225e8c4f9d0b3f86908d42a61e611f406e13817d16240f94f52f49359022100f4c768dd89c6435afd3834ae2c882465ade92d7e1cc5c2c2c3d8d25c41b3ea61014104ce66c9f5068b715b62cc1622572cd98a08812d8ca01563045263c3e7af6b997e603e8e62041c4eb82dfd386a3412c34c334c34eb3c76fb0e37483fc72323f807ffffffff01b0ad5407000000001976a9146a4e7d5f798e90e84db9244d4805459f8727594388ac00000000' )) # Verify 2-of-3 tx from Testnet psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def test2of2MultiSigTx(self): tx1 = PyTx().unserialize( hex_to_binary( '010000000189a0022c8291b4328338ec95179612b8ebf72067051de019a6084fb97eae0ebe000000004a4930460221009627882154854e3de066943ba96faba02bb8b80c1670a0a30d0408caa49f03df022100b625414510a2a66ebb43fffa3f4023744695380847ee1073117ec90cb60f2c8301ffffffff0210c18d0000000000434104a701496f10db6aa8acbb6a7aa14d62f4925f8da03de7f0262010025945f6ebcc3efd55b6aa4bc6f811a0dc1bbdd2644bdd81c8a63766aa11f650cd7736bbcaf8ac001bb7000000000043526b006b7dac7ca914fc1243972b59c1726735d3c5cca40e415039dce9879a6c936b7dac7ca914375dd72e03e7b5dbb49f7e843b7bef4a2cc2ce9e879a6c936b6c6ca200000000' )) tx2 = PyTx().unserialize( hex_to_binary( '01000000011c9608650a912be7fa88eecec664e6fbfa4b676708697fa99c28b3370005f32d01000000fd1701483045022017462c29efc9158cf26f2070d444bb2b087b8a0e6287a9274fa36fad30c46485022100c6d4cc6cd504f768389637df71c1ccd452e0691348d0f418130c31da8cc2a6e8014104e83c1d4079a1b36417f0544063eadbc44833a992b9667ab29b4ff252d8287687bad7581581ae385854d4e5f1fcedce7de12b1aec1cb004cabb2ec1f3de9b2e60493046022100fdc7beb27de0c3a53fbf96df7ccf9518c5fe7873eeed413ce17e4c0e8bf9c06e022100cc15103b3c2e1f49d066897fe681a12e397e87ed7ee39f1c8c4a5fef30f4c2c60141047cf315904fcc2e3e2465153d39019e0d66a8aaec1cec1178feb10d46537427239fd64b81e41651e89b89fefe6a23561d25dddc835395dd3542f83b32a1906aebffffffff01c0d8a700000000001976a914fc1243972b59c1726735d3c5cca40e415039dce988ac00000000' )) # Verify 2-of-2 tx from Testnet psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def testCreateTx(self): addrA = PyBtcAddress().createFromPrivateKey(hex_to_int('aa' * 32)) addrB = PyBtcAddress().createFromPrivateKey(hex_to_int('bb' * 32)) # This TxIn will be completely ignored, so it can contain garbage txinA = PyTxIn() txinA.outpoint = PyOutPoint().unserialize(hex_to_binary('00' * 36)) txinA.binScript = hex_to_binary('99' * 4) txinA.intSeq = hex_to_int('ff' * 4) # test binary unpacker in unserialize testTxIn = PyTxIn().unserialize(txinA.serialize()) self.assertEqual(txinA.getScript(), testTxIn.getScript()) self.assertEqual(txinA.intSeq, testTxIn.intSeq) self.assertEqual(txinA.outpoint.txHash, testTxIn.outpoint.txHash) txoutA = PyTxOut() txoutA.value = 50 * ONE_BTC txoutA.binScript = '\x76\xa9\x14' + addrA.getAddr160() + '\x88\xac' # Test pprint print '\nTest pretty print PyTxIn, expect PrevTXHash all 0s' testTxIn.pprint() # test binary unpacker in unserialize testTxOut = PyTxOut().unserialize(txoutA.serialize()) self.assertEqual(txoutA.getScript(), testTxOut.getScript()) self.assertEqual(txoutA.value, testTxOut.getValue()) # Test pprint print '\nTest pretty print PyTxOut' testTxOut.pprint() tx1 = PyTx() tx1.version = 1 tx1.numInputs = 1 tx1.inputs = [txinA] tx1.numOutputs = 1 tx1.outputs = [txoutA] tx1.locktime = 0 tx1hash = tx1.getHash() recipientList = tx1.makeRecipientsList() self.assertEqual(len(recipientList), 1) self.assertEqual(recipientList[0][0], 0) self.assertEqual(recipientList[0][1], 50 * ONE_BTC) self.assertEqual(tx1.getHashHex(), binary_to_hex(tx1hash)) # Creating transaction to send coins from A to B tx2 = PyCreateAndSignTx_old([[addrA, tx1, 0]], [[addrB, 50 * ONE_BTC]]) psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def testCreateTx(self): addrA = PyBtcAddress().createFromPrivateKey(hex_to_int('aa' * 32)) addrB = PyBtcAddress().createFromPrivateKey(hex_to_int('bb' * 32)) # This TxIn will be completely ignored, so it can contain garbage txinA = PyTxIn() txinA.outpoint = PyOutPoint().unserialize(hex_to_binary('00'*36)) txinA.binScript = hex_to_binary('99'*4) txinA.intSeq = hex_to_int('ff'*4) # test binary unpacker in unserialize testTxIn = PyTxIn().unserialize(txinA.serialize()) self.assertEqual(txinA.getScript(), testTxIn.getScript()) self.assertEqual(txinA.intSeq, testTxIn.intSeq) self.assertEqual(txinA.outpoint.txHash, testTxIn.outpoint.txHash) txoutA = PyTxOut() txoutA.value = 50 * ONE_BTC txoutA.binScript = '\x76\xa9\x14' + addrA.getAddr160() + '\x88\xac' # Test pprint print '\nTest pretty print PyTxIn, expect PrevTXHash all 0s' testTxIn.pprint() # test binary unpacker in unserialize testTxOut = PyTxOut().unserialize(txoutA.serialize()) self.assertEqual(txoutA.getScript(), testTxOut.getScript()) self.assertEqual(txoutA.value, testTxOut.getValue()) # Test pprint print '\nTest pretty print PyTxOut' testTxOut.pprint() tx1 = PyTx() tx1.version = 1 tx1.numInputs = 1 tx1.inputs = [txinA] tx1.numOutputs = 1 tx1.outputs = [txoutA] tx1.locktime = 0 tx1hash = tx1.getHash() recipientList = tx1.makeRecipientsList() self.assertEqual(len(recipientList), 1) self.assertEqual(recipientList[0][0], 0) self.assertEqual(recipientList[0][1], 50 * ONE_BTC) self.assertEqual(tx1.getHashHex(), binary_to_hex(tx1hash)) # Creating transaction to send coins from A to B tx2 = PyCreateAndSignTx_old( [[ addrA, tx1, 0 ]], [[addrB, 50*ONE_BTC]]) psp = PyScriptProcessor() psp.setTxObjects(tx1, tx2, 0) self.assertTrue(psp.verifyTransactionValid())
def setUp(self): self.fileA = os.path.join(ARMORY_HOME_DIR, 'armory_%s_.wallet' % TEST_WALLET_ID) self.fileB = os.path.join(ARMORY_HOME_DIR, 'armory_%s_backup.wallet' % TEST_WALLET_ID) self.fileAupd = os.path.join( ARMORY_HOME_DIR, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID) self.fileBupd = os.path.join( ARMORY_HOME_DIR, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID) self.removeFileList( [self.fileA, self.fileB, self.fileAupd, self.fileBupd]) # We need a controlled test, so we script the all the normally-random stuff self.privKey = SecureBinaryData('\xaa' * 32) self.privKey2 = SecureBinaryData('\x33' * 32) self.chainstr = SecureBinaryData('\xee' * 32) theIV = SecureBinaryData(hex_to_binary('77' * 16)) self.passphrase = SecureBinaryData('A self.passphrase') self.passphrase2 = SecureBinaryData('A new self.passphrase') self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \ plainRootKey=self.privKey, \ chaincode=self.chainstr, \ IV=theIV, \ shortLabel=TEST_WALLET_NAME, \ longLabel=TEST_WALLET_DESCRIPTION) self.jsonServer = Armory_Json_Rpc_Server(self.wallet) TheBDM.registerWallet(self.wallet)
def setUp(self): self.shortlabel = 'TestWallet1' self.wltID ='3VB8XSoY' self.fileA = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet' % self.wltID) self.fileB = os.path.join(self.armoryHomeDir, 'armory_%s_backup.wallet' % self.wltID) self.fileAupd = os.path.join(self.armoryHomeDir, 'armory_%s_backup_unsuccessful.wallet' % self.wltID) self.fileBupd = os.path.join(self.armoryHomeDir, 'armory_%s_update_unsuccessful.wallet' % self.wltID) self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd]) # We need a controlled test, so we script the all the normally-random stuff self.privKey = SecureBinaryData('\xaa'*32) self.privKey2 = SecureBinaryData('\x33'*32) self.chainstr = SecureBinaryData('\xee'*32) theIV = SecureBinaryData(hex_to_binary('77'*16)) self.passphrase = SecureBinaryData('A self.passphrase') self.passphrase2 = SecureBinaryData('A new self.passphrase') self.wlt = PyBtcWallet().createNewWallet(withEncrypt=False, \ plainRootKey=self.privKey, \ chaincode=self.chainstr, \ IV=theIV, \ shortLabel=self.shortlabel, armoryHomeDir = self.armoryHomeDir)
def searchItem(): searchString = str(self.searchEntry.text()) if len(searchString) > 0: likelyDataType = isLikelyDataType(searchString) for wltID, wlt in self.main.walletMap.iteritems(): if wlt.hasAddr(searchString): searchHash = searchString if likelyDataType == DATATYPE.Hex \ else addrStr_to_hash160(searchString)[1] dialog = DlgAddressInfo(wlt, searchHash, main=self.main) dialog.exec_() break if likelyDataType == DATATYPE.Hex: walletLedger = wlt.cppWallet.getTxLedger() txHashToFind = hex_to_binary(searchString, endOut=BIGENDIAN) txFound = False for entry in walletLedger: if entry.getTxHash() == txHashToFind: cppTx = TheBDM.getTxByHash(txHashToFind) serializedCppTx = cppTx.serialize() pytx = PyTx().unserialize(serializedCppTx) DlgDispTxInfo(pytx, wlt, self.main, self.main).exec_() txFound = True break if txFound: break
def searchItem(): searchString = str(self.searchEntry.text()) if len(searchString) > 0: likelyDataType = isLikelyDataType(searchString) for wltID, wlt in self.main.walletMap.iteritems(): if wlt.hasAddr(searchString): searchHash = searchString if likelyDataType == DATATYPE.Hex \ else addrStr_to_hash160(searchString)[1] dialog = DlgAddressInfo(wlt, searchHash, main=self.main) dialog.exec_() break if likelyDataType == DATATYPE.Hex: walletLedger = wlt.cppWallet.getTxLedger() txHashToFind = hex_to_binary(searchString, endOut=BIGENDIAN) txFound = False for entry in walletLedger: if entry.getTxHash() == txHashToFind: cppTx = TheBDM.getTxByHash(txHashToFind) serializedCppTx = cppTx.serialize() pytx = PyTx().unserialize(serializedCppTx) DlgDispTxInfo(pytx, wlt, self.main, self.main).exec_() txFound = True break if txFound: break
def callSplitSecret(self, secretHex, M, N, nbytes=1): secret = hex_to_binary(secretHex) print '\nSplitting secret into %d-of-%d: secret=%s' % (M,N,secretHex) tstart = RightNow() out = SplitSecret(secret, M, N) tsplit = RightNow() - tstart print 'Fragments:' for i in range(len(out)): x = binary_to_hex(out[i][0]) y = binary_to_hex(out[i][1]) print ' Fragment %d: [%s, %s]' % (i+1,x,y) trecon = 0 print 'Reconstructing secret from various subsets of fragments...' for i in range(10): shuffle(out) tstart = RightNow() reconstruct = ReconstructSecret(out, M, nbytes) trecon += RightNow() - tstart print ' The reconstructed secret is:', binary_to_hex(reconstruct) self.assertEqual(binary_to_hex(reconstruct), secretHex) print 'Splitting secret took: %0.5f sec' % tsplit print 'Reconstructing takes: %0.5f sec' % (trecon/10) # Running tests with "python <module name>" will NOT work for any Armory tests # You must run tests with "python -m unittest <module name>" or run all tests with "python -m unittest discover" # if __name__ == "__main__": # unittest.main()
def setUp(self): self.shortlabel = 'TestWallet1' self.wltID = '3VB8XSoY' if USE_TESTNET else '3VB8XSmd' self.fileA = os.path.join(ARMORY_HOME_DIR, 'armory_%s_.wallet' % self.wltID) self.fileB = os.path.join(ARMORY_HOME_DIR, 'armory_%s_backup.wallet' % self.wltID) self.fileAupd = os.path.join( ARMORY_HOME_DIR, 'armory_%s_backup_unsuccessful.wallet' % self.wltID) self.fileBupd = os.path.join( ARMORY_HOME_DIR, 'armory_%s_update_unsuccessful.wallet' % self.wltID) self.removeFileList( [self.fileA, self.fileB, self.fileAupd, self.fileBupd]) # We need a controlled test, so we script the all the normally-random stuff self.privKey = SecureBinaryData('\xaa' * 32) self.privKey2 = SecureBinaryData('\x33' * 32) self.chainstr = SecureBinaryData('\xee' * 32) theIV = SecureBinaryData(hex_to_binary('77' * 16)) self.passphrase = SecureBinaryData('A self.passphrase') self.passphrase2 = SecureBinaryData('A new self.passphrase') self.wlt = PyBtcWallet().createNewWallet(withEncrypt=False, \ plainRootKey=self.privKey, \ chaincode=self.chainstr, \ IV=theIV, \ shortLabel=self.shortlabel)
def setUp(self): self.verifyBlockHeight() self.fileA = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet' % TEST_WALLET_ID) self.fileB = os.path.join(self.armoryHomeDir, 'armory_%s_backup.wallet' % TEST_WALLET_ID) self.fileAupd = os.path.join(self.armoryHomeDir, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID) self.fileBupd = os.path.join(self.armoryHomeDir, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID) self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd]) # We need a controlled test, so we script the all the normally-random stuff self.privKey = SecureBinaryData('\xaa'*32) self.privKey2 = SecureBinaryData('\x33'*32) self.chainstr = SecureBinaryData('\xee'*32) theIV = SecureBinaryData(hex_to_binary('77'*16)) self.passphrase = SecureBinaryData('A self.passphrase') self.passphrase2 = SecureBinaryData('A new self.passphrase') self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \ plainRootKey=self.privKey, \ chaincode=self.chainstr, \ IV=theIV, \ shortLabel=TEST_WALLET_NAME, \ longLabel=TEST_WALLET_DESCRIPTION, armoryHomeDir = self.armoryHomeDir) self.jsonServer = Armory_Json_Rpc_Server(self.wallet) TheBDM.registerWallet(self.wallet)
def testSimpleAddress(self): # Execute the tests with Satoshi's public key from the Bitcoin specification page satoshiPubKeyHex = '04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284' addrPiece1Hex = '65a4358f4691660849d9f235eb05f11fabbd69fa' addrPiece1Bin = hex_to_binary(addrPiece1Hex) satoshiAddrStr = hash160_to_addrStr(addrPiece1Bin) saddr = PyBtcAddress().createFromPublicKey( hex_to_binary(satoshiPubKeyHex) ) print '\tAddr calc from pubkey: ', saddr.calculateAddrStr() self.assertTrue(checkAddrStrValid(satoshiAddrStr)) testAddr = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY) msg = int_to_binary(39029348428) theHash = hash256(msg) derSig = testAddr.generateDERSignature(theHash) # Testing ECDSA signing & verification -- arbitrary binary strings: self.assertTrue(testAddr.verifyDERSignature( theHash, derSig))
def testVerifyEncryptionKey(self): testAddr = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY) theIV = SecureBinaryData(hex_to_binary(INIT_VECTOR)) testAddr.enableKeyEncryption(theIV) self.assertFalse(testAddr.verifyEncryptionKey(FAKE_KDF_OUTPUT1)) testAddr.lock(FAKE_KDF_OUTPUT1) self.assertTrue(testAddr.verifyEncryptionKey(FAKE_KDF_OUTPUT1)) self.assertFalse(testAddr.verifyEncryptionKey(FAKE_KDF_OUTPUT2))
def testSimpleAddress(self): # Execute the tests with Satoshi's public key from the Bitcoin specification page satoshiPubKeyHex = '04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284' addrPiece1Hex = '65a4358f4691660849d9f235eb05f11fabbd69fa' addrPiece1Bin = hex_to_binary(addrPiece1Hex) satoshiAddrStr = hash160_to_addrStr(addrPiece1Bin) saddr = PyBtcAddress().createFromPublicKey( hex_to_binary(satoshiPubKeyHex)) print '\tAddr calc from pubkey: ', saddr.calculateAddrStr() self.assertTrue(checkAddrStrValid(satoshiAddrStr)) testAddr = PyBtcAddress().createFromPlainKeyData( PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY) msg = int_to_binary(39029348428) theHash = hash256(msg) derSig = testAddr.generateDERSignature(theHash) # Testing ECDSA signing & verification -- arbitrary binary strings: self.assertTrue(testAddr.verifyDERSignature(theHash, derSig))
def testSerializeUnserialize(self): tx1 = PyTx().unserialize(tx1raw) tx2 = PyTx().unserialize(BinaryUnpacker(tx2raw)) tx1again = tx1.serialize() tx2again = tx2.serialize() self.assertEqual(tx1again, tx1raw) self.assertEqual(tx2again, tx2raw) blk = PyBlock().unserialize(hex_to_binary(hexBlock)) blockReHex = binary_to_hex(blk.serialize()) self.assertEqual(hexBlock, blockReHex) binRoot = blk.blockData.getMerkleRoot() self.assertEqual(blk.blockHeader.merkleRoot, blk.blockData.merkleRoot)
def testSerializeUnserialize(self): tx1 = PyTx().unserialize(tx1raw) tx2 = PyTx().unserialize(BinaryUnpacker(tx2raw)) tx1again = tx1.serialize() tx2again = tx2.serialize() self.assertEqual(tx1again, tx1raw) self.assertEqual(tx2again, tx2raw) blk = PyBlock().unserialize( hex_to_binary(hexBlock) ) blockReHex = binary_to_hex(blk.serialize()) self.assertEqual(hexBlock, blockReHex) binRoot = blk.blockData.getMerkleRoot() self.assertEqual(blk.blockHeader.merkleRoot, blk.blockData.merkleRoot)
def buildCorruptWallet(self, walletPath): from armoryengine.PyBtcWallet import PyBtcWallet crpWlt = PyBtcWallet() crpWlt.createNewWallet(walletPath, securePassphrase='testing', doRegisterWithBDM=False) #not registering with the BDM, have to fill the wallet address pool manually crpWlt.fillAddressPool(100) #grab the last computed address lastaddr = crpWlt.addrMap[crpWlt.lastComputedChainAddr160] #corrupt the pubkey PubKey = hex_to_binary( '0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455' ) lastaddr.binPublicKey65 = SecureBinaryData(PubKey) crpWlt.addrMap[crpWlt.lastComputedChainAddr160] = lastaddr crpWlt.fillAddressPool(200) #insert a gap and inconsistent encryption newAddr = PyBtcAddress() newAddr.chaincode = lastaddr.chaincode newAddr.chainIndex = 250 PrivKey = hex_to_binary( 'e3b0c44298fc1c149afbf4c8996fb92427ae41e5978fe51ca495991b7852b855') newAddr.binPrivKey32_Plain = SecureBinaryData(PrivKey) newAddr.binPublicKey65 = CryptoECDSA().ComputePublicKey( newAddr.binPrivKey32_Plain) newAddr.addrStr20 = newAddr.binPublicKey65.getHash160() newAddr.isInitialized = True crpWlt.addrMap[newAddr.addrStr20] = newAddr crpWlt.lastComputedChainAddr160 = newAddr.addrStr20 crpWlt.fillAddressPool(250) #TODO: corrupt a private key #break an address entry at binary level return crpWlt.uniqueIDB58
def setUp(self): self.verifyBlockHeight() self.fileA = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet' % TEST_WALLET_ID) self.fileB = os.path.join(self.armoryHomeDir, 'armory_%s_backup.wallet' % TEST_WALLET_ID) self.fileAupd = os.path.join( self.armoryHomeDir, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID) self.fileBupd = os.path.join( self.armoryHomeDir, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID) self.removeFileList( [self.fileA, self.fileB, self.fileAupd, self.fileBupd]) # We need a controlled test, so we script the all the normally-random stuff self.privKey = SecureBinaryData('\xaa' * 32) self.privKey2 = SecureBinaryData('\x33' * 32) self.chainstr = SecureBinaryData('\xee' * 32) theIV = SecureBinaryData(hex_to_binary('77' * 16)) self.passphrase = SecureBinaryData('A self.passphrase') self.passphrase2 = SecureBinaryData('A new self.passphrase') #register a callback TheBDM.registerCppNotification(self.armoryDTestCallback) #flag to check on wallet scan status self.walletIsScanned = False #create the wallet self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \ plainRootKey=self.privKey, \ chaincode=self.chainstr, \ IV=theIV, \ shortLabel=TEST_WALLET_NAME, \ longLabel=TEST_WALLET_DESCRIPTION, armoryHomeDir = self.armoryHomeDir) self.jsonServer = Armory_Json_Rpc_Server(self.wallet) #register it self.wallet.registerWallet() #wait on scan for 2 min then raise if the scan hasn't finished yet i = 0 while not self.walletIsScanned: time.sleep(0.5) i += 1 if i >= 60 * 4: raise RuntimeError( "Timeout waiting for TheBDM to register the wallet.")
def setUp(self): self.verifyBlockHeight() self.fileA = os.path.join(self.armoryHomeDir, 'armory_%s_.wallet' % TEST_WALLET_ID) self.fileB = os.path.join(self.armoryHomeDir, 'armory_%s_backup.wallet' % TEST_WALLET_ID) self.fileAupd = os.path.join(self.armoryHomeDir, 'armory_%s_backup_unsuccessful.wallet' % TEST_WALLET_ID) self.fileBupd = os.path.join(self.armoryHomeDir, 'armory_%s_update_unsuccessful.wallet' % TEST_WALLET_ID) self.removeFileList([self.fileA, self.fileB, self.fileAupd, self.fileBupd]) # We need a controlled test, so we script the all the normally-random stuff self.privKey = SecureBinaryData('\xaa'*32) self.privKey2 = SecureBinaryData('\x33'*32) self.chainstr = SecureBinaryData('\xee'*32) theIV = SecureBinaryData(hex_to_binary('77'*16)) self.passphrase = SecureBinaryData('A self.passphrase') self.passphrase2 = SecureBinaryData('A new self.passphrase') #register a callback TheBDM.registerCppNotification(self.armoryDTestCallback) #flag to check on wallet scan status self.walletIsScanned = False #create the wallet self.wallet = PyBtcWallet().createNewWallet(withEncrypt=False, \ plainRootKey=self.privKey, \ chaincode=self.chainstr, \ IV=theIV, \ shortLabel=TEST_WALLET_NAME, \ longLabel=TEST_WALLET_DESCRIPTION, armoryHomeDir = self.armoryHomeDir) self.jsonServer = Armory_Json_Rpc_Server(self.wallet) #register it self.wallet.registerWallet() #wait on scan for 2 min then raise if the scan hasn't finished yet i = 0 while not self.walletIsScanned: time.sleep(0.5) i += 1 if i >= 60*4: raise RuntimeError("Timeout waiting for TheBDM to register the wallet.")
def testTouch(self): testAddr = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY) theIV = SecureBinaryData(hex_to_binary(INIT_VECTOR)) testAddr.enableKeyEncryption(theIV) rightNow = RightNow() testAddr.touch(rightNow) self.assertEqual(testAddr.timeRange[0], long(rightNow)) self.assertEqual(testAddr.timeRange[1], long(rightNow)) testAddr.touch(0) self.assertEqual(testAddr.timeRange[0], long(0)) self.assertEqual(testAddr.timeRange[1], long(rightNow)) testAddr.touch(blkNum=TEST_BLOCK_NUM) self.assertEqual(testAddr.blkRange[0], TEST_BLOCK_NUM) self.assertEqual(testAddr.blkRange[1], TOP_TIAB_BLOCK) testAddr.touch(blkNum=0) self.assertEqual(testAddr.blkRange[0], 0) self.assertEqual(testAddr.blkRange[1], TOP_TIAB_BLOCK) # Cover the case where the blkRange[0] starts at 0 testAddr.touch(blkNum=TEST_BLOCK_NUM) self.assertEqual(testAddr.blkRange[0], TEST_BLOCK_NUM) self.assertEqual(testAddr.blkRange[1], TOP_TIAB_BLOCK)
def callSplitSecret(self, secretHex, M, N, nbytes=1): secret = hex_to_binary(secretHex) print '\nSplitting secret into %d-of-%d: secret=%s' % (M,N,secretHex) tstart = RightNow() out = SplitSecret(secret, M, N) tsplit = RightNow() - tstart print 'Fragments:' for i in range(len(out)): x = binary_to_hex(out[i][0]) y = binary_to_hex(out[i][1]) print ' Fragment %d: [%s, %s]' % (i+1,x,y) trecon = 0 print 'Reconstructing secret from various subsets of fragments...' for i in range(10): shuffle(out) tstart = RightNow() reconstruct = ReconstructSecret(out, M, nbytes) trecon += RightNow() - tstart print ' The reconstructed secret is:', binary_to_hex(reconstruct) self.assertEqual(binary_to_hex(reconstruct), secretHex) print 'Splitting secret took: %0.5f sec' % tsplit print 'Reconstructing takes: %0.5f sec' % (trecon/10)
def testPyBtcWallet(self): self.wlt.addrPoolSize = 5 # No block chain loaded so this should return -1 # self.assertEqual(self.wlt.detectHighestUsedIndex(True), -1) self.assertEqual(self.wlt.kdfKey, None) self.assertEqual(binary_to_hex(self.wlt.addrMap['ROOT'].addrStr20), WALLET_ROOT_ADDR ) ############################################################################# # (1) Getting a new address: newAddr = self.wlt.getNextUnusedAddress() self.wlt.pprint(indent=' '*5) self.assertEqual(binary_to_hex(newAddr.addrStr20), NEW_UNUSED_ADDR) # (1) Re-reading wallet from file, compare the two wallets wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # (2)Testing unencrypted wallet import-address' originalLength = len(self.wlt.linearAddr160List) self.wlt.importExternalAddressData(privKey=self.privKey2) self.assertEqual(len(self.wlt.linearAddr160List), originalLength+1) # (2) Re-reading wallet from file, compare the two wallets wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) self.assertTrue(self.wlt.isEqualTo(wlt2)) # (2a)Testing deleteImportedAddress # Wallet size before delete:', os.path.getsize(self.wlt.walletPath) # Addresses before delete:', len(self.wlt.linearAddr160List) toDelete160 = convertKeyDataToAddress(self.privKey2) self.wlt.deleteImportedAddress(toDelete160) self.assertEqual(len(self.wlt.linearAddr160List), originalLength) # (2a) Reimporting address for remaining tests # Wallet size before reimport:', os.path.getsize(self.wlt.walletPath) self.wlt.importExternalAddressData(privKey=self.privKey2) self.assertEqual(len(self.wlt.linearAddr160List), originalLength+1) # (2b)Testing ENCRYPTED wallet import-address privKey3 = SecureBinaryData('\xbb'*32) privKey4 = SecureBinaryData('\x44'*32) self.chainstr2 = SecureBinaryData('\xdd'*32) theIV2 = SecureBinaryData(hex_to_binary('66'*16)) self.passphrase2= SecureBinaryData('hello') wltE = PyBtcWallet().createNewWallet(withEncrypt=True, \ plainRootKey=privKey3, \ securePassphrase=self.passphrase2, \ chaincode=self.chainstr2, \ IV=theIV2, \ shortLabel=self.shortlabel) # We should have thrown an error about importing into a locked wallet... self.assertRaises(WalletLockError, wltE.importExternalAddressData, privKey=self.privKey2) wltE.unlock(securePassphrase=self.passphrase2) wltE.importExternalAddressData(privKey=self.privKey2) # (2b) Re-reading wallet from file, compare the two wallets wlt2 = PyBtcWallet().readWalletFile(wltE.walletPath) self.assertTrue(wltE.isEqualTo(wlt2)) # (2b) Unlocking wlt2 after re-reading locked-import-wallet wlt2.unlock(securePassphrase=self.passphrase2) self.assertFalse(wlt2.isLocked) ############################################################################# # Now play with encrypted wallets # *********************************************************************' # (3)Testing conversion to encrypted wallet kdfParams = self.wlt.computeSystemSpecificKdfParams(0.1) self.wlt.changeKdfParams(*kdfParams) self.assertEqual(self.wlt.kdf.getSalt(), kdfParams[2]) self.wlt.changeWalletEncryption( securePassphrase=self.passphrase ) self.assertEqual(self.wlt.kdf.getSalt(), kdfParams[2]) # (3) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) # NOTE: this isEqual operation compares the serializations # of the wallet addresses, which only contains the # encrypted versions of the private keys. However, # self.wlt is unlocked and contains the plaintext keys, too # while wlt2 does not. self.wlt.lock() for key in self.wlt.addrMap: self.assertTrue(self.wlt.addrMap[key].isLocked) self.assertEqual(self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') ############################################################################# # (4)Testing changing self.passphrase on encrypted wallet', self.wlt.unlock( securePassphrase=self.passphrase ) for key in self.wlt.addrMap: self.assertFalse(self.wlt.addrMap[key].isLocked) self.assertNotEqual(self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') # ...to same self.passphrase' origKdfKey = self.wlt.kdfKey self.wlt.changeWalletEncryption( securePassphrase=self.passphrase ) self.assertEqual(origKdfKey, self.wlt.kdfKey) # (4)And now testing new self.passphrase...' self.wlt.changeWalletEncryption( securePassphrase=self.passphrase2 ) self.assertNotEqual(origKdfKey, self.wlt.kdfKey) # (4) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # (5)Testing changing KDF on encrypted wallet' self.wlt.unlock( securePassphrase=self.passphrase2 ) MEMORY_REQT_BYTES = 1024 NUM_ITER = 999 SALT_ALL_0 ='00'*32 self.wlt.changeKdfParams(MEMORY_REQT_BYTES, NUM_ITER, hex_to_binary(SALT_ALL_0), self.passphrase2) self.assertEqual(self.wlt.kdf.getMemoryReqtBytes(), MEMORY_REQT_BYTES) self.assertEqual(self.wlt.kdf.getNumIterations(), NUM_ITER) self.assertEqual(self.wlt.kdf.getSalt().toHexStr(), SALT_ALL_0) self.wlt.changeWalletEncryption( securePassphrase=self.passphrase2 ) # I don't know why this shouldn't be '' # Commenting out because it's a broken assertion # self.assertNotEqual(origKdfKey.toHexStr(), '') # (5) Get new address from locked wallet' # Locking wallet' self.wlt.lock() for i in range(10): self.wlt.getNextUnusedAddress() self.assertEqual(len(self.wlt.addrMap), originalLength+13) # (5) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # !!! #forkOnlineWallet() # (6)Testing forking encrypted wallet for online mode' self.wlt.forkOnlineWallet('OnlineVersionOfEncryptedWallet.bin') wlt2.readWalletFile('OnlineVersionOfEncryptedWallet.bin') for key in wlt2.addrMap: self.assertTrue(self.wlt.addrMap[key].isLocked) self.assertEqual(self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') # (6)Getting a new addresses from both wallets' for i in range(self.wlt.addrPoolSize*2): self.wlt.getNextUnusedAddress() wlt2.getNextUnusedAddress() newaddr1 = self.wlt.getNextUnusedAddress() newaddr2 = wlt2.getNextUnusedAddress() self.assertTrue(newaddr1.getAddr160() == newaddr2.getAddr160()) self.assertEqual(len(wlt2.addrMap), 3*originalLength+14) # (6) Re-reading wallet from file, compare the two wallets wlt3 = PyBtcWallet().readWalletFile('OnlineVersionOfEncryptedWallet.bin') self.assertTrue(wlt3.isEqualTo(wlt2)) ############################################################################# # (7)Testing removing wallet encryption' # Wallet is locked? ', self.wlt.isLocked self.wlt.unlock(securePassphrase=self.passphrase2) self.wlt.changeWalletEncryption( None ) for key in self.wlt.addrMap: self.assertFalse(self.wlt.addrMap[key].isLocked) self.assertNotEqual(self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') # (7) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # \n' # *********************************************************************' # (8)Doing interrupt tests to test wallet-file-update recovery' def hashfile(fn): f = open(fn,'r') d = hash256(f.read()) f.close() return binary_to_hex(d[:8]) def verifyFileStatus(fileAExists = True, fileBExists = True, \ fileAupdExists = True, fileBupdExists = True): self.assertEqual(os.path.exists(self.fileA), fileAExists) self.assertEqual(os.path.exists(self.fileB), fileBExists) self.assertEqual(os.path.exists(self.fileAupd), fileAupdExists) self.assertEqual(os.path.exists(self.fileBupd), fileBupdExists) correctMainHash = hashfile(self.fileA) try: self.wlt.interruptTest1 = True self.wlt.getNextUnusedAddress() except InterruptTestError: # Interrupted!' pass self.wlt.interruptTest1 = False # (8a)Interrupted getNextUnusedAddress on primary file update' verifyFileStatus(True, True, False, True) # (8a)Do consistency check on the wallet' self.wlt.doWalletFileConsistencyCheck() verifyFileStatus(True, True, False, False) self.assertEqual(correctMainHash, hashfile(self.fileA)) try: self.wlt.interruptTest2 = True self.wlt.getNextUnusedAddress() except InterruptTestError: # Interrupted!' pass self.wlt.interruptTest2 = False # (8b)Interrupted getNextUnusedAddress on between primary/backup update' verifyFileStatus(True, True, True, True) # (8b)Do consistency check on the wallet' self.wlt.doWalletFileConsistencyCheck() verifyFileStatus(True, True, False, False) self.assertEqual(hashfile(self.fileA), hashfile(self.fileB)) # (8c) Try interrupting at state 3' verifyFileStatus(True, True, False, False) try: self.wlt.interruptTest3 = True self.wlt.getNextUnusedAddress() except InterruptTestError: # Interrupted!' pass self.wlt.interruptTest3 = False # (8c)Interrupted getNextUnusedAddress on backup file update' verifyFileStatus(True, True, True, False) # (8c)Do consistency check on the wallet' self.wlt.doWalletFileConsistencyCheck() verifyFileStatus(True, True, False, False) self.assertEqual(hashfile(self.fileA), hashfile(self.fileB)) ############################################################################# # \n' # *********************************************************************' # (9)Checksum-based byte-error correction tests!' # (9)Start with a good primary and backup file...' # (9a)Open primary wallet, change second byte in KDF' wltfile = open(self.wlt.walletPath,'r+b') wltfile.seek(326) wltfile.write('\xff') wltfile.close() # (9a)Byte changed, file hashes:' verifyFileStatus(True, True, False, False) # (9a)Try to read wallet from file, should correct KDF error, write fix' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # \n' # *********************************************************************' # (9b)Change a byte in each checksummed field in root addr' wltfile = open(self.wlt.walletPath,'r+b') wltfile.seek(838); wltfile.write('\xff') wltfile.seek(885); wltfile.write('\xff') wltfile.seek(929); wltfile.write('\xff') wltfile.seek(954); wltfile.write('\xff') wltfile.seek(1000); wltfile.write('\xff') wltfile.close() # (9b) New file hashes...' verifyFileStatus(True, True, False, False) # (9b)Try to read wallet from file, should correct address errors' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # \n' # *********************************************************************' # (9c)Change a byte in each checksummed field, of first non-root addr' wltfile = open(self.wlt.walletPath,'r+b') wltfile.seek(1261+21+838); wltfile.write('\xff') wltfile.seek(1261+21+885); wltfile.write('\xff') wltfile.seek(1261+21+929); wltfile.write('\xff') wltfile.seek(1261+21+954); wltfile.write('\xff') wltfile.seek(1261+21+1000); wltfile.write('\xff') wltfile.close() # (9c) New file hashes...' verifyFileStatus(True, True, False, False) # (9c)Try to read wallet from file, should correct address errors' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # \n' # *********************************************************************' # (9d)Now butcher the CHECKSUM, see if correction works' wltfile = open(self.wlt.walletPath,'r+b') wltfile.seek(977); wltfile.write('\xff') wltfile.close() # (9d) New file hashes...' verifyFileStatus(True, True, False, False) # (9d)Try to read wallet from file, should correct address errors' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # *******' # (9z) Test comment I/O' comment1 = 'This is my normal unit-testing address.' comment2 = 'This is fake tx... no tx has this hash.' comment3 = comment1 + ' Corrected!' hash1 = '\x1f'*20 # address160 hash2 = '\x2f'*32 # tx hash self.wlt.setComment(hash1, comment1) self.wlt.setComment(hash2, comment2) self.wlt.setComment(hash1, comment3) wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) c3 = wlt2.getComment(hash1) c2 = wlt2.getComment(hash2) self.assertEqual(c3, comment3) self.assertEqual(c2, comment2)
from armoryengine.Block import PyBlock from armoryengine.PyBtcAddress import PyBtcAddress from armoryengine.Script import PyScriptProcessor from armoryengine.Transaction import PyTx, PyTxIn, PyOutPoint, PyTxOut, \ PyCreateAndSignTx, getMultisigScriptInfo, BlockComponent,\ PyCreateAndSignTx_old from pytest.Tiab import TiabTest # Unserialize an reserialize tx1raw = hex_to_binary( \ '01000000016290dce984203b6a5032e543e9e272d8bce934c7de4d15fa0fe44d' 'd49ae4ece9010000008b48304502204f2fa458d439f957308bca264689aa175e' '3b7c5f78a901cb450ebd20936b2c500221008ea3883a5b80128e55c9c6070aa6' '264e1e0ce3d18b7cd7e85108ce3d18b7419a0141044202550a5a6d3bb81549c4' 'a7803b1ad59cdbba4770439a4923624a8acfc7d34900beb54a24188f7f0a4068' '9d905d4847cc7d6c8d808a457d833c2d44ef83f76bffffffff0242582c0a0000' '00001976a914c1b4695d53b6ee57a28647ce63e45665df6762c288ac80d1f008' '000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') tx2raw = hex_to_binary( \ '0100000001f658dbc28e703d86ee17c9a2d3b167a8508b082fa0745f55be5144' 'a4369873aa010000008c49304602210041e1186ca9a41fdfe1569d5d807ca7ff' '6c5ffd19d2ad1be42f7f2a20cdc8f1cc0221003366b5d64fe81e53910e156914' '091d12646bc0d1d662b7a65ead3ebe4ab8f6c40141048d103d81ac9691cf13f3' 'fc94e44968ef67b27f58b27372c13108552d24a6ee04785838f34624b294afee' '83749b64478bb8480c20b242c376e77eea2b3dc48b4bffffffff0200e1f50500' '0000001976a9141b00a2f6899335366f04b277e19d777559c35bc888ac40aeeb' '02000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') multiTx1raw = hex_to_binary( \
def testEncryptedAddress(self): # test serialization and unserialization of an empty PyBtcAddrss # Should serialize to a string that starts with 20 bytes of zeros # Unserialize should throw an UnserializeError caused by checksum mismatch emptyBtcAddr = PyBtcAddress() emptyBtcAddrSerialized = emptyBtcAddr.serialize() self.assertEqual(emptyBtcAddrSerialized[:20], hex_to_binary('00'*20)) self.assertRaises(UnserializeError, PyBtcAddress().unserialize, emptyBtcAddrSerialized) # Test non-crashing testAddr1 = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20) testAddr2 = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, chksum=PRIVATE_CHECKSUM) testAddr3 = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY) testAddr4 = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY, skipCheck=True) testAddr5 = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, skipPubCompute=True) testString = testAddr1.toString() self.assertTrue(len(testString) > 0) testAddr = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20, publicKey65=PUBLIC_KEY) serializedAddr1 = testAddr.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr1) serializedRetest1 = retestAddr.serialize() self.assertEqual(serializedAddr1, serializedRetest1) theIV = SecureBinaryData(hex_to_binary(INIT_VECTOR)) testAddr.enableKeyEncryption(theIV) testAddr.lock(FAKE_KDF_OUTPUT1) self.assertTrue(testAddr.useEncryption) self.assertTrue(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), '') self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR1) serializedAddr2 = testAddr.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr2) serializedRetest2 = retestAddr.serialize() self.assertEqual(serializedAddr2, serializedRetest2) testAddr.unlock(FAKE_KDF_OUTPUT1) self.assertFalse(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) testAddr.changeEncryptionKey(None, FAKE_KDF_OUTPUT1) self.assertTrue(testAddr.useEncryption) self.assertFalse(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR1) # Save off this data for a later test addr20_1 = testAddr.getAddr160() encryptedKey1 = testAddr.binPrivKey32_Encr encryptionIV1 = testAddr.binInitVect16 plainPubKey1 = testAddr.binPublicKey65 # OP(Key1 --> Unencrypted) testAddr.changeEncryptionKey(FAKE_KDF_OUTPUT1, None) self.assertFalse(testAddr.useEncryption) self.assertFalse(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), '') # OP(Unencrypted --> Key2) if not testAddr.isKeyEncryptionEnabled(): testAddr.enableKeyEncryption(theIV) testAddr.changeEncryptionKey(None, FAKE_KDF_OUTPUT2) self.assertTrue(testAddr.useEncryption) self.assertFalse(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR2) # Save off this data for a later test addr20_2 = testAddr.getAddr160() encryptedKey2 = testAddr.binPrivKey32_Encr encryptionIV2 = testAddr.binInitVect16 plainPubKey2 = testAddr.binPublicKey65 # OP(Key2 --> Key1) testAddr.changeEncryptionKey(FAKE_KDF_OUTPUT2, FAKE_KDF_OUTPUT1) self.assertTrue(testAddr.useEncryption) self.assertFalse(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR1) # OP(Key1 --> Lock --> Key2) testAddr.lock(FAKE_KDF_OUTPUT1) testAddr.changeEncryptionKey(FAKE_KDF_OUTPUT1, FAKE_KDF_OUTPUT2) self.assertTrue(testAddr.useEncryption) self.assertTrue(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), '') self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR2) # OP(Key2 --> Lock --> Unencrypted) testAddr.changeEncryptionKey(FAKE_KDF_OUTPUT2, None) self.assertFalse(testAddr.useEncryption) self.assertFalse(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), '') # Encryption Key Tests: self.assertEqual(testAddr.serializePlainPrivateKey(), PRIVATE_KEY.toBinStr()) # Test loading pre-encrypted key data testAddr = PyBtcAddress().createFromEncryptedKeyData(addr20_1, encryptedKey1, encryptionIV1) self.assertTrue(testAddr.useEncryption) self.assertTrue(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), '') self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR1) # OP(EncrAddr --> Unlock1) testAddr.unlock(FAKE_KDF_OUTPUT1) self.assertTrue(testAddr.useEncryption) self.assertFalse(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR1) # OP(Unlock1 --> Lock1) testAddr.lock() self.assertTrue(testAddr.useEncryption) self.assertTrue(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), '') self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR1) # OP(Lock1 --> Lock2) testAddr.changeEncryptionKey(FAKE_KDF_OUTPUT1, FAKE_KDF_OUTPUT2) self.assertTrue(testAddr.useEncryption) self.assertTrue(testAddr.isLocked) self.assertEqual(testAddr.binPrivKey32_Plain.toHexStr(), '') self.assertEqual(testAddr.binPrivKey32_Encr.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR2) # Test serializing locked wallet from pre-encrypted data' serializedAddr = testAddr.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) ############################################################################# # Now testing chained-key (deterministic) address generation # Test chained priv key generation # Starting with plain key data chaincode = SecureBinaryData(hex_to_binary('ee'*32)) addr0 = PyBtcAddress().createFromPlainKeyData(PRIVATE_KEY, ADDRESS_20) addr0.markAsRootAddr(chaincode) pub0 = addr0.binPublicKey65 # Test serializing address-chain-root serializedAddr = addr0.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) self.assertEqual(retestAddr.binPrivKey32_Plain.toHexStr(), PRIVATE_KEY.toHexStr()) # Generate chained PRIVATE key address # OP(addr[0] --> addr[1]) addr1 = addr0.extendAddressChain() self.assertEqual(addr1.binPrivKey32_Plain.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR3) # OP(addr[0] --> addr[1]) [again]' addr1a = addr0.extendAddressChain() self.assertEqual(addr1a.binPrivKey32_Plain.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR3) # OP(addr[1] --> addr[2]) addr2 = addr1.extendAddressChain() pub2 = addr2.binPublicKey65.copy() priv2 = addr2.binPrivKey32_Plain.copy() self.assertEqual(priv2.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR4) # Addr1.PRIVATE_KEY == Addr1a.PRIVATE_KEY:', self.assertEqual(addr1.binPublicKey65, addr1a.binPublicKey65) # Test serializing priv-key-chained', serializedAddr = addr2.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) ############################################################################# # Generate chained PUBLIC key address # addr[0] addr0 = PyBtcAddress().createFromPublicKeyData(pub0) addr0.markAsRootAddr(chaincode) self.assertEqual(addr0.chainIndex, -1) self.assertEqual(addr0.chaincode, chaincode) # Test serializing pub-key-only-root', serializedAddr = addr0.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) # OP(addr[0] --> addr[1])' addr1 = addr0.extendAddressChain() self.assertEqual(addr1.binPrivKey32_Plain.toHexStr(), '') # OP(addr[1] --> addr[2])' addr2 = addr1.extendAddressChain() pub2a = addr2.binPublicKey65.copy() self.assertEqual(addr2.binPrivKey32_Plain.toHexStr(), '') self.assertEqual(pub2a.toHexStr(), TEST_PUB_KEY1) # Addr2.PublicKey == Addr2a.PublicKey:' # Test serializing pub-key-from-chain' serializedAddr = addr2.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) ############################################################################# # Generate chained keys from locked addresses addr0 = PyBtcAddress().createFromPlainKeyData( PRIVATE_KEY, \ willBeEncr=True, IV16=theIV) addr0.markAsRootAddr(chaincode) # OP(addr[0] plain) # Test serializing unlocked addr-chain-root serializedAddr = addr0.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) self.assertFalse(retestAddr.useEncryption) # OP(addr[0] locked) addr0.lock(FAKE_KDF_OUTPUT1) self.assertEqual(addr0.binPrivKey32_Plain.toHexStr(), '') # OP(addr[0] w/Key --> addr[1]) addr1 = addr0.extendAddressChain(FAKE_KDF_OUTPUT1, newIV=theIV) self.assertEqual(addr1.binPrivKey32_Plain.toHexStr(), '') # OP(addr[1] w/Key --> addr[2]) addr2 = addr1.extendAddressChain(FAKE_KDF_OUTPUT1, newIV=theIV) addr2.unlock(FAKE_KDF_OUTPUT1) priv2a = addr2.binPrivKey32_Plain.copy() addr2.lock() self.assertEqual(addr2.binPrivKey32_Plain.toHexStr(), '') # Addr2.priv == Addr2a.priv: self.assertEqual(priv2, priv2a) # Test serializing chained address from locked root serializedAddr = addr2.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) ############################################################################# # Generate chained keys from locked addresses, no unlocking addr0 = PyBtcAddress().createFromPlainKeyData( PRIVATE_KEY, \ willBeEncr=True, IV16=theIV) addr0.markAsRootAddr(chaincode) # OP(addr[0] locked) addr0.lock(FAKE_KDF_OUTPUT1) self.assertEqual(addr0.binPrivKey32_Plain.toHexStr(), '') # OP(addr[0] locked --> addr[1] locked)' addr1 = addr0.extendAddressChain(newIV=theIV) self.assertEqual(addr1.binPrivKey32_Plain.toHexStr(), '') # OP(addr[1] locked --> addr[2] locked) addr2 = addr1.extendAddressChain(newIV=theIV) pub2b = addr2.binPublicKey65.copy() self.assertEqual(addr2.binPrivKey32_Plain.toHexStr(), '') self.assertEqual(pub2b.toHexStr(), TEST_PUB_KEY1) # Addr2.Pub == Addr2b.pub: # Test serializing priv-key-bearing address marked for unlock serializedAddr = addr2.serialize() retestAddr = PyBtcAddress().unserialize(serializedAddr) serializedRetest = retestAddr.serialize() self.assertEqual(serializedAddr, serializedRetest) addr2.unlock(FAKE_KDF_OUTPUT1) priv2b = addr2.binPrivKey32_Plain.copy() # OP(addr[2] locked --> unlocked) self.assertEqual(priv2b.toHexStr(), TEST_ADDR1_PRIV_KEY_ENCR4) addr2.lock() # OP(addr[2] unlocked --> locked)' # Addr2.priv == Addr2b.priv: self.assertEqual(priv2, priv2b)
f.seek(pos) return result MAGIC_HEX_STRING = "f9beb4d9" MAGIC_NUMBER_LENGTH = 4 VERSION_LENGTH = 4 BLOCK_SIZE_LENGTH = 4 TX_OUT_HASH_LENGTH = 32 TX_OUT_INDEX_LENGTH = 4 SEQUENCE_LENGTH = 4 LOCKTIME_LENGTH = 4 SATOSHI_LENGTH = 8 HEADER_LENGTH = 80 HEX_32_BYTE_0 = "0000000000000000000000000000000000000000000000000000000000000000" BIN_32_BYTE_0 = hex_to_binary(HEX_32_BYTE_0) HEX_32_BYTE_ALL_F = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" DIFFICULTY_NUMERATOR = 0x00000000FFFF0000000000000000000000000000000000000000000000000000 getHighestTarget = lambda bits: float(hex_to_int(binary_to_hex(bits, BIGENDIAN)[2:8]) * 2**(8*(hex_to_int(binary_to_hex(bits, BIGENDIAN)[:2]) - 3))) def calculateDifficulty(bits): return DIFFICULTY_NUMERATOR / getHighestTarget(bits) def parseBlockHeader(blkHdrBinary): binunpack = BinaryUnpacker(blkHdrBinary) return BlockHeader(binunpack.get(UINT32), binunpack.get(BINARY_CHUNK, 32), binunpack.get(BINARY_CHUNK, 32), binunpack.get(UINT32), binunpack.get(UINT32),
checkAddrStrValid, hash256, UnserializeError, hash160_to_addrStr from armoryengine.PyBtcAddress import PyBtcAddress sys.argv.append('--nologging') INIT_VECTOR = '77'*16 TEST_ADDR1_PRIV_KEY_ENCR1 = '500c41607d79c766859e6d9726ef1ea0fdf095922f3324454f6c4c34abcb23a5' TEST_ADDR1_PRIV_KEY_ENCR2 = '7966cf5886494246cc5aaf7f1a4a2777cd6126612e7029d79ef9df47f6d6927d' TEST_ADDR1_PRIV_KEY_ENCR3 = '0db5c1e9a8d1ebc0525bdb534626033b948804a9a34871d67bf58a3df11d6888' TEST_ADDR1_PRIV_KEY_ENCR4 = '5db1314a20ae9fc978477ab3fe16ab17b246d813a541ecdd4143fcf082b19407' TEST_PUB_KEY1 = '046c35e36776e997883ad4269dcc0696b10d68f6864ae73b8ad6ad03e879e43062a0139095ece3bd653b809fa7e8c7d78ffe6fac75a84c8283d8a000890bfc879d' # Create an address to use for all subsequent tests PRIVATE_KEY = SecureBinaryData(hex_to_binary('aa'*32)) PRIVATE_CHECKSUM = PRIVATE_KEY.getHash256()[:4] PUBLIC_KEY = CryptoECDSA().ComputePublicKey(PRIVATE_KEY) ADDRESS_20 = PUBLIC_KEY.getHash160() TEST_BLOCK_NUM = 100 # We pretend that we plugged some passphrases through a KDF FAKE_KDF_OUTPUT1 = SecureBinaryData( hex_to_binary('11'*32) ) FAKE_KDF_OUTPUT2 = SecureBinaryData( hex_to_binary('22'*32) ) class PyBtcAddressTest(TiabTest): # TODO: This test needs more verification of the results. def testEncryptedAddress(self):
def testUnpackUnserializePyOutPoint(self): outpoint = PyOutPoint().unserialize(BinaryUnpacker(ALL_ZERO_OUTPOINT)) self.assertEqual(outpoint.txHash, hex_to_binary('00'*32)) self.assertEqual(outpoint.txOutIndex, 0)
def testGetrawtransaction(self): actualRawTx = self.jsonServer.jsonrpc_getrawtransaction(TX_ID1) pyTx = PyTx().unserialize(hex_to_binary(actualRawTx)) self.assertEquals(TX_ID1, binary_to_hex(pyTx.getHash(), BIGENDIAN))
# Get the input print "Getting input from transaction..." transaction = bitcoinTransaction(UTX) print str(transaction) trustedInput = app.getTrustedInput(transaction, UTXO_INDEX) # Start composing transaction print "Creating transaction on BTChip..." app.startUntrustedTransaction(True, 0, [trustedInput], bytearray(REDEEMSCRIPT.decode('hex'))) app.finalizeInputFull(OUTPUT) print "Signing..." signature = app.untrustedHashSign(KEYPATH, "") sigStr = hex_to_binary(binascii.hexlify(signature)) # Put signature back into armory transaction tx.insertSignature(sigStr, hex_to_binary(pubKey)) print "\n\nSignature summary and signing status:\n\n" tx.pprint() tx.evaluateSigningStatus().pprint() print "\n\nRaw transaction:\n\n" # doVerifySigs = tx.evaluateSigningStatus().canBroadcast # print binary_to_hex(tx.getSignedPyTx(doVerifySigs=doVerifySigs).serialize()) # Unfortunately Armory doesn't appear to be able to verify these, so you're best off broadcasting the raw
ONE_BTC from armoryengine.BinaryUnpacker import BinaryUnpacker from armoryengine.Block import PyBlock from armoryengine.PyBtcAddress import PyBtcAddress from armoryengine.Script import PyScriptProcessor from armoryengine.Transaction import PyTx, PyTxIn, PyOutPoint, PyTxOut, \ PyCreateAndSignTx, getMultisigScriptInfo, BlockComponent,\ PyCreateAndSignTx_old from pytest.Tiab import TiabTest # Unserialize an reserialize tx1raw = hex_to_binary( \ '01000000016290dce984203b6a5032e543e9e272d8bce934c7de4d15fa0fe44d' 'd49ae4ece9010000008b48304502204f2fa458d439f957308bca264689aa175e' '3b7c5f78a901cb450ebd20936b2c500221008ea3883a5b80128e55c9c6070aa6' '264e1e0ce3d18b7cd7e85108ce3d18b7419a0141044202550a5a6d3bb81549c4' 'a7803b1ad59cdbba4770439a4923624a8acfc7d34900beb54a24188f7f0a4068' '9d905d4847cc7d6c8d808a457d833c2d44ef83f76bffffffff0242582c0a0000' '00001976a914c1b4695d53b6ee57a28647ce63e45665df6762c288ac80d1f008' '000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') tx2raw = hex_to_binary( \ '0100000001f658dbc28e703d86ee17c9a2d3b167a8508b082fa0745f55be5144' 'a4369873aa010000008c49304602210041e1186ca9a41fdfe1569d5d807ca7ff' '6c5ffd19d2ad1be42f7f2a20cdc8f1cc0221003366b5d64fe81e53910e156914' '091d12646bc0d1d662b7a65ead3ebe4ab8f6c40141048d103d81ac9691cf13f3' 'fc94e44968ef67b27f58b27372c13108552d24a6ee04785838f34624b294afee' '83749b64478bb8480c20b242c376e77eea2b3dc48b4bffffffff0200e1f50500' '0000001976a9141b00a2f6899335366f04b277e19d777559c35bc888ac40aeeb' '02000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') multiTx1raw = hex_to_binary( \
def testWalletRecovery(self): #run recovery on broken wallet recThread = PyBtcWalletRecovery().RecoverWallet(self.corruptWallet, \ 'testing', RECOVERMODE.Full, \ returnError = 'Dict') recThread.join() brkWltResult = recThread.output self.assertTrue(len(brkWltResult['sequenceGaps'])==1, \ "Sequence Gap Undetected") self.assertTrue(len(brkWltResult['forkedPublicKeyChain'])==2, \ "Address Chain Forks Undetected") self.assertTrue(len(brkWltResult['unmatchedPair'])==100, \ "Unmatched Priv/Pub Key Undetected") self.assertTrue(len(brkWltResult['misc'])==50, \ "Wallet Encryption Inconsistency Undetected") self.assertTrue(brkWltResult['nErrors']==153, \ "Unexpected Errors Found") #check obfuscated keys yield the valid key #grab root key badWlt = PyBtcWallet() badWlt.readWalletFile(self.corruptWallet, False, False) rootAddr = badWlt.addrMap['ROOT'] SecurePassphrase = SecureBinaryData('testing') secureKdfOutput = badWlt.kdf.DeriveKey(SecurePassphrase) #HMAC Q rootAddr.unlock(secureKdfOutput) Q = rootAddr.binPrivKey32_Plain.toBinStr() nonce = 0 while 1: hmacQ = HMAC256(Q, 'LogMult%d' % nonce) if binary_to_int(hmacQ, BIGENDIAN) < SECP256K1_ORDER: hmacQ = SecureBinaryData(hmacQ) break nonce = nonce +1 #Bad Private Keys import operator badKeys = [addrObj for addrObj in (sorted(badWlt.addrMap.values(), key=operator.attrgetter('chainIndex')))] #run through obdsPrivKey for i in range(0, len(brkWltResult['privMult'])): obfsPKey = SecureBinaryData( hex_to_binary(brkWltResult['privMult'][i])) pKey = CryptoECDSA().ECMultiplyScalars(obfsPKey.toBinStr(), \ hmacQ.toBinStr()) try: badKeys[i+201].unlock(secureKdfOutput) except: continue self.assertTrue(binary_to_hex(pKey) == \ badKeys[i+201].binPrivKey32_Plain.toHexStr(), \ 'key mult error') #run recovery on recovered wallet recThread = PyBtcWalletRecovery().RecoverWallet( \ 'armory_%s_RECOVERED.wallet' % self.wltID, \ 'testing', RECOVERMODE.Full, \ returnError = 'Dict') recThread.join() rcvWltResult = recThread.output self.assertTrue(rcvWltResult['nErrors']==0, "Unexpected Errors Found") self.assertTrue(len(rcvWltResult['negativeImports'])==50, \ "Missing neg Imports")
def testUnpackUnserializePyOutPoint(self): outpoint = PyOutPoint().unserialize(BinaryUnpacker(ALL_ZERO_OUTPOINT)) self.assertEqual(outpoint.txHash, hex_to_binary('00' * 32)) self.assertEqual(outpoint.txOutIndex, 0)
from armoryengine.BinaryUnpacker import BinaryUnpacker from armoryengine.Block import PyBlock from armoryengine.PyBtcAddress import PyBtcAddress from armoryengine.Script import PyScriptProcessor from armoryengine.Transaction import PyTx, PyTxIn, PyOutPoint, PyTxOut, \ PyCreateAndSignTx, getMultisigScriptInfo, BlockComponent,\ PyCreateAndSignTx_old # Unserialize an reserialize tx1raw = hex_to_binary( \ '01000000016290dce984203b6a5032e543e9e272d8bce934c7de4d15fa0fe44d' 'd49ae4ece9010000008b48304502204f2fa458d439f957308bca264689aa175e' '3b7c5f78a901cb450ebd20936b2c500221008ea3883a5b80128e55c9c6070aa6' '264e1e0ce3d18b7cd7e85108ce3d18b7419a0141044202550a5a6d3bb81549c4' 'a7803b1ad59cdbba4770439a4923624a8acfc7d34900beb54a24188f7f0a4068' '9d905d4847cc7d6c8d808a457d833c2d44ef83f76bffffffff0242582c0a0000' '00001976a914c1b4695d53b6ee57a28647ce63e45665df6762c288ac80d1f008' '000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') tx2raw = hex_to_binary( \ '0100000001f658dbc28e703d86ee17c9a2d3b167a8508b082fa0745f55be5144' 'a4369873aa010000008c49304602210041e1186ca9a41fdfe1569d5d807ca7ff' '6c5ffd19d2ad1be42f7f2a20cdc8f1cc0221003366b5d64fe81e53910e156914' '091d12646bc0d1d662b7a65ead3ebe4ab8f6c40141048d103d81ac9691cf13f3' 'fc94e44968ef67b27f58b27372c13108552d24a6ee04785838f34624b294afee' '83749b64478bb8480c20b242c376e77eea2b3dc48b4bffffffff0200e1f50500' '0000001976a9141b00a2f6899335366f04b277e19d777559c35bc888ac40aeeb' '02000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') multiTx1raw = hex_to_binary( \
def testGetrawtransaction(self): actualRawTx = self.jsonServer.jsonrpc_getrawtransaction(TX_ID1) pyTx = PyTx().unserialize(hex_to_binary(actualRawTx)) self.assertEquals(TX_ID1, binary_to_hex(pyTx.getHash(), BIGENDIAN))
print "Your pubkey: " + pubKey # Get the input print "Getting input from transaction..." transaction = bitcoinTransaction(UTX) print str(transaction) trustedInput = app.getTrustedInput(transaction, UTXO_INDEX) # Start composing transaction print "Creating transaction on BTChip..." app.startUntrustedTransaction(True, 0, [trustedInput], bytearray(REDEEMSCRIPT.decode('hex'))) app.finalizeInputFull(OUTPUT) print "Signing..." signature = app.untrustedHashSign(KEYPATH, "") sigStr = hex_to_binary(binascii.hexlify(signature)) # Put signature back into armory transaction tx.insertSignature(sigStr, hex_to_binary(pubKey)) print "\n\nSignature summary and signing status:\n\n" tx.pprint() tx.evaluateSigningStatus().pprint() print "\n\nRaw transaction:\n\n" # doVerifySigs = tx.evaluateSigningStatus().canBroadcast # print binary_to_hex(tx.getSignedPyTx(doVerifySigs=doVerifySigs).serialize()) # Unfortunately Armory doesn't appear to be able to verify these, so you're best off broadcasting the raw
def testMerkle(): txAHash = hex_to_binary('aa'*32) txBHash = hex_to_binary('bb'*32) txCHash = hex_to_binary('cc'*32) answer = hex_to_binary('d6f226837f442e34974d01825cbac711f4c358d1f564747d3d7203a2d4e94619') print 'PASSED' if computeMerkleRoot([txAHash, txBHash, txCHash], 1) == answer else 'FAILED'
def testPyBtcWallet(self): self.wlt.addrPoolSize = 5 # No block chain loaded so this should return -1 # self.assertEqual(self.wlt.detectHighestUsedIndex(True), -1) self.assertEqual(self.wlt.kdfKey, None) self.assertEqual(binary_to_hex(self.wlt.addrMap['ROOT'].addrStr20), WALLET_ROOT_ADDR) ############################################################################# # (1) Getting a new address: newAddr = self.wlt.getNextUnusedAddress() self.wlt.pprint(indent=' ' * 5) self.assertEqual(binary_to_hex(newAddr.addrStr20), NEW_UNUSED_ADDR) # (1) Re-reading wallet from file, compare the two wallets wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # (2)Testing unencrypted wallet import-address' originalLength = len(self.wlt.linearAddr160List) self.wlt.importExternalAddressData(privKey=self.privKey2) self.assertEqual(len(self.wlt.linearAddr160List), originalLength + 1) # (2) Re-reading wallet from file, compare the two wallets wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) self.assertTrue(self.wlt.isEqualTo(wlt2)) # (2a)Testing deleteImportedAddress # Wallet size before delete:', os.path.getsize(self.wlt.walletPath) # Addresses before delete:', len(self.wlt.linearAddr160List) toDelete160 = convertKeyDataToAddress(self.privKey2) self.wlt.deleteImportedAddress(toDelete160) self.assertEqual(len(self.wlt.linearAddr160List), originalLength) # (2a) Reimporting address for remaining tests # Wallet size before reimport:', os.path.getsize(self.wlt.walletPath) self.wlt.importExternalAddressData(privKey=self.privKey2) self.assertEqual(len(self.wlt.linearAddr160List), originalLength + 1) # (2b)Testing ENCRYPTED wallet import-address privKey3 = SecureBinaryData('\xbb' * 32) privKey4 = SecureBinaryData('\x44' * 32) self.chainstr2 = SecureBinaryData('\xdd' * 32) theIV2 = SecureBinaryData(hex_to_binary('66' * 16)) self.passphrase2 = SecureBinaryData('hello') wltE = PyBtcWallet().createNewWallet(withEncrypt=True, \ plainRootKey=privKey3, \ securePassphrase=self.passphrase2, \ chaincode=self.chainstr2, \ IV=theIV2, \ shortLabel=self.shortlabel) # We should have thrown an error about importing into a locked wallet... self.assertRaises(WalletLockError, wltE.importExternalAddressData, privKey=self.privKey2) wltE.unlock(securePassphrase=self.passphrase2) wltE.importExternalAddressData(privKey=self.privKey2) # (2b) Re-reading wallet from file, compare the two wallets wlt2 = PyBtcWallet().readWalletFile(wltE.walletPath) self.assertTrue(wltE.isEqualTo(wlt2)) # (2b) Unlocking wlt2 after re-reading locked-import-wallet wlt2.unlock(securePassphrase=self.passphrase2) self.assertFalse(wlt2.isLocked) ############################################################################# # Now play with encrypted wallets # *********************************************************************' # (3)Testing conversion to encrypted wallet kdfParams = self.wlt.computeSystemSpecificKdfParams(0.1) self.wlt.changeKdfParams(*kdfParams) self.assertEqual(self.wlt.kdf.getSalt(), kdfParams[2]) self.wlt.changeWalletEncryption(securePassphrase=self.passphrase) self.assertEqual(self.wlt.kdf.getSalt(), kdfParams[2]) # (3) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) # NOTE: this isEqual operation compares the serializations # of the wallet addresses, which only contains the # encrypted versions of the private keys. However, # self.wlt is unlocked and contains the plaintext keys, too # while wlt2 does not. self.wlt.lock() for key in self.wlt.addrMap: self.assertTrue(self.wlt.addrMap[key].isLocked) self.assertEqual( self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') ############################################################################# # (4)Testing changing self.passphrase on encrypted wallet', self.wlt.unlock(securePassphrase=self.passphrase) for key in self.wlt.addrMap: self.assertFalse(self.wlt.addrMap[key].isLocked) self.assertNotEqual( self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') # ...to same self.passphrase' origKdfKey = self.wlt.kdfKey self.wlt.changeWalletEncryption(securePassphrase=self.passphrase) self.assertEqual(origKdfKey, self.wlt.kdfKey) # (4)And now testing new self.passphrase...' self.wlt.changeWalletEncryption(securePassphrase=self.passphrase2) self.assertNotEqual(origKdfKey, self.wlt.kdfKey) # (4) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # (5)Testing changing KDF on encrypted wallet' self.wlt.unlock(securePassphrase=self.passphrase2) MEMORY_REQT_BYTES = 1024 NUM_ITER = 999 SALT_ALL_0 = '00' * 32 self.wlt.changeKdfParams(MEMORY_REQT_BYTES, NUM_ITER, hex_to_binary(SALT_ALL_0), self.passphrase2) self.assertEqual(self.wlt.kdf.getMemoryReqtBytes(), MEMORY_REQT_BYTES) self.assertEqual(self.wlt.kdf.getNumIterations(), NUM_ITER) self.assertEqual(self.wlt.kdf.getSalt().toHexStr(), SALT_ALL_0) self.wlt.changeWalletEncryption(securePassphrase=self.passphrase2) # I don't know why this shouldn't be '' # Commenting out because it's a broken assertion # self.assertNotEqual(origKdfKey.toHexStr(), '') # (5) Get new address from locked wallet' # Locking wallet' self.wlt.lock() for i in range(10): self.wlt.getNextUnusedAddress() self.assertEqual(len(self.wlt.addrMap), originalLength + 13) # (5) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # !!! #forkOnlineWallet() # (6)Testing forking encrypted wallet for online mode' self.wlt.forkOnlineWallet('OnlineVersionOfEncryptedWallet.bin') wlt2.readWalletFile('OnlineVersionOfEncryptedWallet.bin') for key in wlt2.addrMap: self.assertTrue(self.wlt.addrMap[key].isLocked) self.assertEqual( self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') # (6)Getting a new addresses from both wallets' for i in range(self.wlt.addrPoolSize * 2): self.wlt.getNextUnusedAddress() wlt2.getNextUnusedAddress() newaddr1 = self.wlt.getNextUnusedAddress() newaddr2 = wlt2.getNextUnusedAddress() self.assertTrue(newaddr1.getAddr160() == newaddr2.getAddr160()) self.assertEqual(len(wlt2.addrMap), 3 * originalLength + 14) # (6) Re-reading wallet from file, compare the two wallets wlt3 = PyBtcWallet().readWalletFile( 'OnlineVersionOfEncryptedWallet.bin') self.assertTrue(wlt3.isEqualTo(wlt2)) ############################################################################# # (7)Testing removing wallet encryption' # Wallet is locked? ', self.wlt.isLocked self.wlt.unlock(securePassphrase=self.passphrase2) self.wlt.changeWalletEncryption(None) for key in self.wlt.addrMap: self.assertFalse(self.wlt.addrMap[key].isLocked) self.assertNotEqual( self.wlt.addrMap[key].binPrivKey32_Plain.toHexStr(), '') # (7) Re-reading wallet from file, compare the two wallets' wlt2 = PyBtcWallet().readWalletFile(self.wlt.getWalletPath()) self.assertTrue(self.wlt.isEqualTo(wlt2)) ############################################################################# # \n' # *********************************************************************' # (8)Doing interrupt tests to test wallet-file-update recovery' def hashfile(fn): f = open(fn, 'r') d = hash256(f.read()) f.close() return binary_to_hex(d[:8]) def verifyFileStatus(fileAExists = True, fileBExists = True, \ fileAupdExists = True, fileBupdExists = True): self.assertEqual(os.path.exists(self.fileA), fileAExists) self.assertEqual(os.path.exists(self.fileB), fileBExists) self.assertEqual(os.path.exists(self.fileAupd), fileAupdExists) self.assertEqual(os.path.exists(self.fileBupd), fileBupdExists) correctMainHash = hashfile(self.fileA) try: self.wlt.interruptTest1 = True self.wlt.getNextUnusedAddress() except InterruptTestError: # Interrupted!' pass self.wlt.interruptTest1 = False # (8a)Interrupted getNextUnusedAddress on primary file update' verifyFileStatus(True, True, False, True) # (8a)Do consistency check on the wallet' self.wlt.doWalletFileConsistencyCheck() verifyFileStatus(True, True, False, False) self.assertEqual(correctMainHash, hashfile(self.fileA)) try: self.wlt.interruptTest2 = True self.wlt.getNextUnusedAddress() except InterruptTestError: # Interrupted!' pass self.wlt.interruptTest2 = False # (8b)Interrupted getNextUnusedAddress on between primary/backup update' verifyFileStatus(True, True, True, True) # (8b)Do consistency check on the wallet' self.wlt.doWalletFileConsistencyCheck() verifyFileStatus(True, True, False, False) self.assertEqual(hashfile(self.fileA), hashfile(self.fileB)) # (8c) Try interrupting at state 3' verifyFileStatus(True, True, False, False) try: self.wlt.interruptTest3 = True self.wlt.getNextUnusedAddress() except InterruptTestError: # Interrupted!' pass self.wlt.interruptTest3 = False # (8c)Interrupted getNextUnusedAddress on backup file update' verifyFileStatus(True, True, True, False) # (8c)Do consistency check on the wallet' self.wlt.doWalletFileConsistencyCheck() verifyFileStatus(True, True, False, False) self.assertEqual(hashfile(self.fileA), hashfile(self.fileB)) ############################################################################# # \n' # *********************************************************************' # (9)Checksum-based byte-error correction tests!' # (9)Start with a good primary and backup file...' # (9a)Open primary wallet, change second byte in KDF' wltfile = open(self.wlt.walletPath, 'r+b') wltfile.seek(326) wltfile.write('\xff') wltfile.close() # (9a)Byte changed, file hashes:' verifyFileStatus(True, True, False, False) # (9a)Try to read wallet from file, should correct KDF error, write fix' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # \n' # *********************************************************************' # (9b)Change a byte in each checksummed field in root addr' wltfile = open(self.wlt.walletPath, 'r+b') wltfile.seek(838) wltfile.write('\xff') wltfile.seek(885) wltfile.write('\xff') wltfile.seek(929) wltfile.write('\xff') wltfile.seek(954) wltfile.write('\xff') wltfile.seek(1000) wltfile.write('\xff') wltfile.close() # (9b) New file hashes...' verifyFileStatus(True, True, False, False) # (9b)Try to read wallet from file, should correct address errors' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # \n' # *********************************************************************' # (9c)Change a byte in each checksummed field, of first non-root addr' wltfile = open(self.wlt.walletPath, 'r+b') wltfile.seek(1261 + 21 + 838) wltfile.write('\xff') wltfile.seek(1261 + 21 + 885) wltfile.write('\xff') wltfile.seek(1261 + 21 + 929) wltfile.write('\xff') wltfile.seek(1261 + 21 + 954) wltfile.write('\xff') wltfile.seek(1261 + 21 + 1000) wltfile.write('\xff') wltfile.close() # (9c) New file hashes...' verifyFileStatus(True, True, False, False) # (9c)Try to read wallet from file, should correct address errors' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # \n' # *********************************************************************' # (9d)Now butcher the CHECKSUM, see if correction works' wltfile = open(self.wlt.walletPath, 'r+b') wltfile.seek(977) wltfile.write('\xff') wltfile.close() # (9d) New file hashes...' verifyFileStatus(True, True, False, False) # (9d)Try to read wallet from file, should correct address errors' wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) verifyFileStatus(True, True, False, False) self.assertNotEqual(hashfile(self.fileA), hashfile(self.fileB)) # *******' # (9z) Test comment I/O' comment1 = 'This is my normal unit-testing address.' comment2 = 'This is fake tx... no tx has this hash.' comment3 = comment1 + ' Corrected!' hash1 = '\x1f' * 20 # address160 hash2 = '\x2f' * 32 # tx hash self.wlt.setComment(hash1, comment1) self.wlt.setComment(hash2, comment2) self.wlt.setComment(hash1, comment3) wlt2 = PyBtcWallet().readWalletFile(self.wlt.walletPath) c3 = wlt2.getComment(hash1) c2 = wlt2.getComment(hash2) self.assertEqual(c3, comment3) self.assertEqual(c2, comment2)
from armoryengine.ArmoryUtils import hex_to_binary, binary_to_hex, hex_to_int, \ ONE_BTC from armoryengine.BinaryUnpacker import BinaryUnpacker from armoryengine.Block import PyBlock from armoryengine.PyBtcAddress import PyBtcAddress from armoryengine.Script import PyScriptProcessor from armoryengine.Transaction import PyTx, PyTxIn, PyOutPoint, PyTxOut, \ PyCreateAndSignTx, getMultisigScriptInfo, BlockComponent,\ PyCreateAndSignTx_old # Unserialize an reserialize tx1raw = hex_to_binary( \ '01000000016290dce984203b6a5032e543e9e272d8bce934c7de4d15fa0fe44d' 'd49ae4ece9010000008b48304502204f2fa458d439f957308bca264689aa175e' '3b7c5f78a901cb450ebd20936b2c500221008ea3883a5b80128e55c9c6070aa6' '264e1e0ce3d18b7cd7e85108ce3d18b7419a0141044202550a5a6d3bb81549c4' 'a7803b1ad59cdbba4770439a4923624a8acfc7d34900beb54a24188f7f0a4068' '9d905d4847cc7d6c8d808a457d833c2d44ef83f76bffffffff0242582c0a0000' '00001976a914c1b4695d53b6ee57a28647ce63e45665df6762c288ac80d1f008' '000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') tx2raw = hex_to_binary( \ '0100000001f658dbc28e703d86ee17c9a2d3b167a8508b082fa0745f55be5144' 'a4369873aa010000008c49304602210041e1186ca9a41fdfe1569d5d807ca7ff' '6c5ffd19d2ad1be42f7f2a20cdc8f1cc0221003366b5d64fe81e53910e156914' '091d12646bc0d1d662b7a65ead3ebe4ab8f6c40141048d103d81ac9691cf13f3' 'fc94e44968ef67b27f58b27372c13108552d24a6ee04785838f34624b294afee' '83749b64478bb8480c20b242c376e77eea2b3dc48b4bffffffff0200e1f50500' '0000001976a9141b00a2f6899335366f04b277e19d777559c35bc888ac40aeeb' '02000000001976a9140e0aec36fe2545fb31a41164fb6954adcd96b34288ac00000000') multiTx1raw = hex_to_binary( \