def T(serialized1, serialized2, are_equal): script1 = CScript(x(serialized1)) script2 = CScript(x(serialized2)) if are_equal: self.assertEqual(script1, script2) else: self.assertNotEqual(script1, script2)
def test_tokenize_roundtrip(self): def T(serialized_script, expected_tokens, test_roundtrip=True): serialized_script = x(serialized_script) script_obj = CScript(serialized_script) actual_tokens = list(script_obj) self.assertEqual(actual_tokens, expected_tokens) if test_roundtrip: recreated_script = CScript(actual_tokens) self.assertEqual(recreated_script, serialized_script) T('', []) # standard pushdata T('00', [OP_0]) T('0100', [b'\x00']) T('4b' + 'ff'*0x4b, [b'\xff'*0x4b]) # non-optimal pushdata T('4c00', [b''], False) T('4c04deadbeef', [x('deadbeef')], False) T('4d0000', [b''], False) T('4d0400deadbeef', [x('deadbeef')], False) T('4e00000000', [b''], False) T('4e04000000deadbeef', [x('deadbeef')], False) # numbers T('00', [0x0]) T('4f', [OP_1NEGATE]) T('51', [0x1]) T('52', [0x2]) T('53', [0x3]) T('54', [0x4]) T('55', [0x5]) T('56', [0x6]) T('57', [0x7]) T('58', [0x8]) T('59', [0x9]) T('5a', [0xa]) T('5b', [0xb]) T('5c', [0xc]) T('5d', [0xd]) T('5e', [0xe]) T('5f', [0xf]) # some opcodes T('9b', [OP_BOOLOR]) T('9a9b', [OP_BOOLAND, OP_BOOLOR]) T('ff', [OP_INVALIDOPCODE]) T('fafbfcfd', [CScriptOp(0xfa), CScriptOp(0xfb), CScriptOp(0xfc), CScriptOp(0xfd)]) # all three types T('512103e2a0e6a91fa985ce4dda7f048fca5ec8264292aed9290594321aa53d37fdea32410478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc345552ae', [1, x('03e2a0e6a91fa985ce4dda7f048fca5ec8264292aed9290594321aa53d37fdea32'), x('0478d430274f8c5ec1321338151e9f27f4c676a008bdf8638d07c0b6be9ab35c71a1518063243acd4dfe96b66e3f2ec8013c8e072cd09b3834a19f81f659cc3455'), 2, OP_CHECKMULTISIG])
def test_bloom_create_insert_key(self): filter = CBloomFilter(2, 0.001, 0, CBloomFilter.UPDATE_ALL) pubkey = x('045B81F0017E2091E2EDCD5EECF10D5BDD120A5514CB3EE65B8447EC18BFC4575C6D5BF415E54E03B1067934A0F0BA76B01C6B9AB227142EE1D543764B69D901E0') pubkeyhash = zcash.core.Hash160(pubkey) filter.insert(pubkey) filter.insert(pubkeyhash) self.assertEqual(filter.serialize(), x('038fc16b080000000000000001'))
def hashtimelockcontract(self, funder, redeemer, commitment, locktime): funderAddr = CBitcoinAddress(funder) redeemerAddr = CBitcoinAddress(redeemer) if type(commitment) == str: commitment = x(commitment) # h = sha256(secret) blocknum = self.zcashd.getblockcount() print("Current blocknum on Zcash: ", blocknum) redeemblocknum = blocknum + locktime print("Redeemblocknum on Zcash: ", redeemblocknum) # can rm op_dup and op_hash160 if you replace addrs with pubkeys (as raw hex/bin data?), and can rm last op_equalverify (for direct pubkey comparison) zec_redeemScript = CScript([ OP_IF, OP_SHA256, commitment, OP_EQUALVERIFY, OP_DUP, OP_HASH160, redeemerAddr, OP_ELSE, redeemblocknum, OP_CHECKLOCKTIMEVERIFY, OP_DROP, OP_DUP, OP_HASH160, funderAddr, OP_ENDIF, OP_EQUALVERIFY, OP_CHECKSIG ]) # print("Redeem script for p2sh contract on Zcash blockchain: ", b2x(zec_redeemScript)) txin_scriptPubKey = zec_redeemScript.to_p2sh_scriptPubKey() # Convert the P2SH scriptPubKey to a base58 Bitcoin address txin_p2sh_address = CBitcoinAddress.from_scriptPubKey( txin_scriptPubKey) p2sh = str(txin_p2sh_address) print("p2sh computed: ", p2sh) # Import address as soon as you create it self.zcashd.importaddress(p2sh, "", False) # Returning all this to be saved locally in p2sh.json return { 'p2sh': p2sh, 'redeemblocknum': redeemblocknum, 'redeemScript': b2x(zec_redeemScript), 'redeemer': redeemer, 'funder': funder, 'locktime': locktime }
def refund(self, contract): fundtx = self.find_transaction_to_address(contract.p2sh) print("Fund tx found in refund: ", fundtx) refundPubKey = self.find_refundAddr(contract) print('refundPubKey: {0}'.format(refundPubKey)) redeemScript = CScript(x(contract.redeemScript)) txin = CMutableTxIn(fundtx['outpoint']) txout = CMutableTxOut(fundtx['amount'] - FEE, refundPubKey.to_scriptPubKey()) # Create the unsigned raw transaction. tx = CMutableTransaction([txin], [txout]) # Set nSequence and nLockTime txin.nSequence = 0 tx.nLockTime = contract.redeemblocknum # Create the unsigned raw transaction. sighash = SignatureHash(redeemScript, tx, 0, SIGHASH_ALL) privkey = self.zcashd.dumpprivkey(refundPubKey) sig = privkey.sign(sighash) + bytes([SIGHASH_ALL]) # Sign without secret txin.scriptSig = CScript([sig, privkey.pub, OP_FALSE, redeemScript]) txin_scriptPubKey = redeemScript.to_p2sh_scriptPubKey() print('Raw redeem transaction hex: {0}'.format(b2x(tx.serialize()))) res = VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH, )) print("Script verified, sending raw transaction... (NOT)", res) txid = self.zcashd.sendrawtransaction(tx) refund_tx = b2x(lx(b2x(txid))) fund_tx = str(fundtx['outpoint']) return {"refund_tx": refund_tx, "fund_tx": fund_tx}
def getblockheader(self, block_hash, verbose=False): """Get block header <block_hash> verbose - If true a dict is returned with the values returned by getblockheader that are not in the block header itself (height, nextblockhash, etc.) Raises IndexError if block_hash is not valid. """ try: block_hash = b2lx(block_hash) except TypeError: raise TypeError( '%s.getblockheader(): block_hash must be bytes; got %r instance' % (self.__class__.__name__, block_hash.__class__)) try: r = self._call('getblockheader', block_hash, verbose) except InvalidAddressOrKeyError as ex: raise IndexError('%s.getblockheader(): %s (%d)' % (self.__class__.__name__, ex.error['message'], ex.error['code'])) if verbose: nextblockhash = None if 'nextblockhash' in r: nextblockhash = lx(r['nextblockhash']) return { 'confirmations': r['confirmations'], 'height': r['height'], 'mediantime': r['mediantime'], 'nextblockhash': nextblockhash, 'chainwork': x(r['chainwork']) } else: return CBlockHeader.deserialize(unhexlify(r))
def redeem(self, contract, fundtx, secret): # TODO: parse the script once, up front. redeemPubKey = self.find_redeemAddr(contract) print('redeemPubKey', redeemPubKey) zec_redeemScript = CScript(x(contract.redeemScript)) txin = CMutableTxIn(fundtx['outpoint']) txout = CMutableTxOut(fundtx['amount'] - FEE, redeemPubKey.to_scriptPubKey()) # Create the unsigned raw transaction. tx = CMutableTransaction([txin], [txout]) sighash = SignatureHash(zec_redeemScript, tx, 0, SIGHASH_ALL) # TODO: figure out how to better protect privkey privkey = self.zcashd.dumpprivkey(redeemPubKey) sig = privkey.sign(sighash) + bytes([SIGHASH_ALL]) print("SECRET", secret) preimage = secret.encode('utf-8') txin.scriptSig = CScript( [sig, privkey.pub, preimage, OP_TRUE, zec_redeemScript]) txin_scriptPubKey = zec_redeemScript.to_p2sh_scriptPubKey() print('Raw redeem transaction hex: ', b2x(tx.serialize())) VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH, )) print("Script verified, sending raw redeem transaction...") txid = self.zcashd.sendrawtransaction(tx) redeem_tx = b2x(lx(b2x(txid))) fund_tx = str(fundtx['outpoint']) return {"redeem_tx": redeem_tx, "fund_tx": fund_tx}
def redeem_contract(self, contract, secret): # How to find redeemScript and redeemblocknum from blockchain? p2sh = contract.p2sh #checking there are funds in the address amount = self.check_funds(p2sh) if (amount == 0): print("Address ", p2sh, " not funded") quit() fundtx = self.find_transaction_to_address(p2sh) amount = fundtx['amount'] / COIN # print("Found fund_tx: ", fundtx) p2sh = P2SHBitcoinAddress(p2sh) if fundtx['address'] == p2sh: print("Found {0} in p2sh {1}, redeeming...".format(amount, p2sh)) # Where can you find redeemblocknum in the transaction? # redeemblocknum = find_redeemblocknum(contract) blockcount = self.zcashd.getblockcount() print("\nCurrent blocknum at time of redeem on Zcash:", blockcount) if blockcount < contract.redeemblocknum: # TODO: parse the script once, up front. redeemPubKey = self.find_redeemAddr(contract) print('redeemPubKey', redeemPubKey) zec_redeemScript = CScript(x(contract.redeemScript)) txin = CMutableTxIn(fundtx['outpoint']) txout = CMutableTxOut(fundtx['amount'] - FEE, redeemPubKey.to_scriptPubKey()) # Create the unsigned raw transaction. tx = CMutableTransaction([txin], [txout]) sighash = SignatureHash(zec_redeemScript, tx, 0, SIGHASH_ALL) # TODO: figure out how to better protect privkey privkey = self.zcashd.dumpprivkey(redeemPubKey) sig = privkey.sign(sighash) + bytes([SIGHASH_ALL]) print("SECRET", secret) preimage = secret.encode('utf-8') txin.scriptSig = CScript( [sig, privkey.pub, preimage, OP_TRUE, zec_redeemScript]) txin_scriptPubKey = zec_redeemScript.to_p2sh_scriptPubKey() print('Raw redeem transaction hex: ', b2x(tx.serialize())) VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH, )) print("Script verified, sending raw redeem transaction...") txid = self.zcashd.sendrawtransaction(tx) redeem_tx = b2x(lx(b2x(txid))) fund_tx = str(fundtx['outpoint']) return {"redeem_tx": redeem_tx, "fund_tx": fund_tx} else: print("nLocktime exceeded, refunding") refundPubKey = self.find_refundAddr(contract) print('refundPubKey', refundPubKey) txid = self.zcashd.sendtoaddress(refundPubKey, fundtx['amount'] - FEE) refund_tx = b2x(lx(b2x(txid))) fund_tx = str(fundtx['outpoint']) return {"refund_tx": refund_tx, "fund_tx": fund_tx} else: print("No contract for this p2sh found in database", p2sh)
def redeem_with_secret(contract, secret): # How to find redeemScript and redeemblocknum from blockchain? # print("Redeeming contract using secret", contract.__dict__) p2sh = contract['p2sh'] minamount = float(contract['amount']) # checking there are funds in the address amount = check_funds(p2sh) if amount < minamount: print ('address ', p2sh, ' not sufficiently funded') return False fundtx = find_transaction_to_address(p2sh) amount = fundtx['amount'] / COIN p2sh = P2SHBitcoinAddress(p2sh) if fundtx['address'] == p2sh: print 'Found {0} in p2sh {1}, redeeming...'.format(amount, p2sh) redeemPubKey = find_redeemAddr(contract) print ('redeemPubKey', redeemPubKey) redeemScript = CScript(x(contract['redeemScript'])) txin = CMutableTxIn(fundtx['outpoint']) txout = CMutableTxOut(fundtx['amount'] - FEE, redeemPubKey.to_scriptPubKey()) # Create the unsigned raw transaction. tx = CMutableTransaction([txin], [txout]) sighash = SignatureHash(redeemScript, tx, 0, SIGHASH_ALL) # TODO: figure out how to better protect privkey privkey = zcashd.dumpprivkey(redeemPubKey) sig = privkey.sign(sighash) + bytes([SIGHASH_ALL]) print ('SECRET', secret) # secret = get_secret() preimage = secret.encode('utf-8') txin.scriptSig = CScript([sig, privkey.pub, preimage, OP_TRUE, redeemScript]) # print("txin.scriptSig", b2x(txin.scriptSig)) txin_scriptPubKey = redeemScript.to_p2sh_scriptPubKey() # print('Redeem txhex', b2x(tx.serialize())) VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH, )) print 'script verified, sending raw tx' txid = zcashd.sendrawtransaction(tx) print ('Txid of submitted redeem tx: ', b2x(lx(b2x(txid)))) return b2x(lx(b2x(txid))) else: print ('No contract for this p2sh found in database', p2sh)
def T(serialized_script, expected_tokens, test_roundtrip=True): serialized_script = x(serialized_script) script_obj = CScript(serialized_script) actual_tokens = list(script_obj) self.assertEqual(actual_tokens, expected_tokens) if test_roundtrip: recreated_script = CScript(actual_tokens) self.assertEqual(recreated_script, serialized_script)
def parse_secret(self, txid): raw = self.zcashd.gettransaction(txid, True)['hex'] decoded = self.zcashd.decoderawtransaction(raw) scriptSig = decoded['vin'][0]['scriptSig'] asm = scriptSig['asm'].split(" ") pubkey = asm[1] secret = x2s(asm[2]) redeemPubkey = P2PKHBitcoinAddress.from_pubkey(x(pubkey)) return secret
def test_create_insert_serialize(self): filter = CBloomFilter(3, 0.01, 0, CBloomFilter.UPDATE_ALL) def T(elem): """Filter contains elem""" elem = x(elem) filter.insert(elem) self.assertTrue(filter.contains(elem)) def F(elem): """Filter does not contain elem""" elem = x(elem) self.assertFalse(filter.contains(elem)) T('99108ad8ed9bb6274d3980bab5a85c048f0950c8') F('19108ad8ed9bb6274d3980bab5a85c048f0950c8') T('b5a2c786d9ef4658287ced5914b37a1b4aa32eee') T('b9300670b4c5366e95b2699e8b18bc75e5f729c5') self.assertEqual(filter.serialize(), x('03614e9b050000000000000001')) deserialized = CBloomFilter.deserialize(x('03614e9b050000000000000001')) self.assertTrue(deserialized.contains(x('99108ad8ed9bb6274d3980bab5a85c048f0950c8'))) self.assertFalse(deserialized.contains(x('19108ad8ed9bb6274d3980bab5a85c048f0950c8'))) self.assertTrue(deserialized.contains(x('b5a2c786d9ef4658287ced5914b37a1b4aa32eee'))) self.assertTrue(deserialized.contains(x('b9300670b4c5366e95b2699e8b18bc75e5f729c5')))
def test_repr(self): def T(script, expected_repr): actual_repr = repr(script) self.assertEqual(actual_repr, expected_repr) T( CScript([]), 'CScript([])') T( CScript([1]), 'CScript([1])') T( CScript([1, 2, 3]), 'CScript([1, 2, 3])') T( CScript([1, x('7ac977d8373df875eceda362298e5d09d4b72b53'), OP_DROP]), "CScript([1, x('7ac977d8373df875eceda362298e5d09d4b72b53'), OP_DROP])") T(CScript(x('0001ff515261ff')), "CScript([0, x('ff'), 1, 2, OP_NOP, OP_INVALIDOPCODE])") # truncated scripts T(CScript(x('6101')), "CScript([OP_NOP, x('')...<ERROR: PUSHDATA(1): truncated data>])") T(CScript(x('614bff')), "CScript([OP_NOP, x('ff')...<ERROR: PUSHDATA(75): truncated data>])") T(CScript(x('614c')), "CScript([OP_NOP, <ERROR: PUSHDATA1: missing data length>])") T(CScript(x('614c0200')), "CScript([OP_NOP, x('00')...<ERROR: PUSHDATA1: truncated data>])")
def parse_secret(txid): raw = zcashd.gettransaction(txid)['hex'] # print("Raw", raw) decoded = zcashd.decoderawtransaction(raw) scriptSig = decoded['vin'][0]['scriptSig'] print("Decoded", scriptSig) asm = scriptSig['asm'].split(" ") pubkey = asm[1] secret = hex2str(asm[2]) redeemPubkey = P2PKHBitcoinAddress.from_pubkey(x(pubkey)) print('redeemPubkey', redeemPubkey) print(secret) return secret
def redeem_after_timelock(contract): print(contract) p2sh = contract.p2sh fundtx = find_transaction_to_address(p2sh) amount = fundtx['amount'] / COIN if (fundtx['address'].__str__() != p2sh): print("no fund transaction found to the contract p2sh address ", p2sh) quit() # print("Found fundtx:", fundtx) # Parsing redeemblocknum from the redeemscript of the p2sh redeemblocknum = find_redeemblocknum(contract) blockcount = zcashd.getblockcount() print("Current block:", blockcount, "Can redeem from block:", redeemblocknum) if (still_locked(contract)): print("too early for redeeming with timelock try again at block", redeemblocknum, "or later") return print("Found {0} in p2sh {1}, redeeming...".format(amount, p2sh)) redeemPubKey = find_refundAddr(contract) print('refundPubKey', redeemPubKey) redeemScript = CScript(x(contract.redeemScript)) txin = CMutableTxIn(fundtx['outpoint']) txout = CMutableTxOut(fundtx['amount'] - FEE, redeemPubKey.to_scriptPubKey()) # Create the unsigned raw transaction. txin.nSequence = 0 tx = CMutableTransaction([txin], [txout]) tx.nLockTime = redeemblocknum sighash = SignatureHash(redeemScript, tx, 0, SIGHASH_ALL) # TODO: figure out how to better protect privkey privkey = zcashd.dumpprivkey(redeemPubKey) sig = privkey.sign(sighash) + bytes([SIGHASH_ALL]) txin.scriptSig = CScript([sig, privkey.pub, OP_FALSE, redeemScript]) # exit() # print("txin.scriptSig", b2x(txin.scriptSig)) txin_scriptPubKey = redeemScript.to_p2sh_scriptPubKey() # print('Redeem txhex', b2x(tx.serialize())) VerifyScript(txin.scriptSig, txin_scriptPubKey, tx, 0, (SCRIPT_VERIFY_P2SH, )) print("script verified, sending raw tx") txid = zcashd.sendrawtransaction(tx) print("Txid of submitted redeem tx: ", b2x(lx(b2x(txid)))) return b2x(lx(b2x(txid)))
def find_recipient(self, contract): # make this dependent on actual fund tx to p2sh, not contract txid = contract.fund_tx raw = self.zcashd.gettransaction(lx(txid), True)['hex'] decoded = self.zcashd.decoderawtransaction(raw) scriptSig = decoded['vin'][0]['scriptSig'] print("Decoded", scriptSig) asm = scriptSig['asm'].split(" ") pubkey = asm[1] initiator = CBitcoinAddress(contract.initiator) fulfiller = CBitcoinAddress(contract.fulfiller) print("Initiator", b2x(initiator)) print("Fulfiller", b2x(fulfiller)) print('pubkey', pubkey) redeemPubkey = P2PKHBitcoinAddress.from_pubkey(x(pubkey)) print('redeemPubkey', redeemPubkey)
def test_to_p2sh_scriptPubKey(self): def T(redeemScript, expected_hex_bytes): redeemScript = CScript(redeemScript) actual_script = redeemScript.to_p2sh_scriptPubKey() self.assertEqual(b2x(actual_script), expected_hex_bytes) T([], 'a914b472a266d0bd89c13706a4132ccfb16f7c3b9fcb87') T([1,x('029b6d2c97b8b7c718c325d7be3ac30f7c9d67651bce0c929f55ee77ce58efcf84'),1,OP_CHECKMULTISIG], 'a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87') T([b'\xff'*517], 'a9140da7fa40ebf248dfbca363c79921bdd665fed5ba87') with self.assertRaises(ValueError): CScript([b'a' * 518]).to_p2sh_scriptPubKey()
def test_create_insert_serialize_with_tweak(self): # Same test as bloom_create_insert_serialize, but we add a nTweak of 100 filter = CBloomFilter(3, 0.01, 2147483649, CBloomFilter.UPDATE_ALL) def T(elem): """Filter contains elem""" elem = x(elem) filter.insert(elem) self.assertTrue(filter.contains(elem)) def F(elem): """Filter does not contain elem""" elem = x(elem) self.assertFalse(filter.contains(elem)) T('99108ad8ed9bb6274d3980bab5a85c048f0950c8') F('19108ad8ed9bb6274d3980bab5a85c048f0950c8') T('b5a2c786d9ef4658287ced5914b37a1b4aa32eee') T('b9300670b4c5366e95b2699e8b18bc75e5f729c5') self.assertEqual(filter.serialize(), x('03ce4299050000000100008001'))
def test_low_s_value(self): sig = x('3045022100b135074e08cc93904a1712b2600d3cb01899a5b1cc7498caa4b8585bcf5f27e7022074ab544045285baef0a63f0fb4c95e577dcbf5c969c0bf47c7da8e478909d669') self.assertTrue(IsLowDERSignature(sig))
def test_high_s_value(self): sig = x('3046022100820121109528efda8bb20ca28788639e5ba5b365e0a84f8bd85744321e7312c6022100a7c86a21446daa405306fe10d0a9906e37d1a2c6b6fdfaaf6700053058029bbe') self.assertFalse(IsLowDERSignature(sig))
def find_refundAddr(contract): scriptarray = parse_script(contract.redeemScript) funder = scriptarray[13] refundAddr = P2PKHBitcoinAddress.from_bytes(x(funder)) return refundAddr
def T(hex_script, expected_result): script = CScript(x(hex_script)) self.assertEqual(script.has_canonical_pushes(), expected_result)
def T(serialized, b): script = CScript(x(serialized)) self.assertEqual(script.is_push_only(), b)
def T(data, expected): data = x(data) expected = x(expected) serialized_data = CScriptOp.encode_op_pushdata(data) self.assertEqual(serialized_data, expected)
def T(hex_pubkey, is_valid, is_fullyvalid, is_compressed): key = CPubKey(x(hex_pubkey)) self.assertEqual(key.is_valid, is_valid) self.assertEqual(key.is_fullyvalid, is_fullyvalid) self.assertEqual(key.is_compressed, is_compressed)
def T(hex_script): script = CScript(x(hex_script)) self.assertEqual(script.has_canonical_pushes(), False)
def find_redeemAddr(contract): scriptarray = parse_script(contract['redeemScript']) redeemer = scriptarray[6] redeemAddr = P2PKHBitcoinAddress.from_bytes(x(redeemer)) return redeemAddr
def T(serialized, b): script = CScript(x(serialized)) self.assertEqual(script.is_unspendable(), b)
def T(hex_script): invalid_script = CScript(x(hex_script)) self.assertFalse(invalid_script.is_push_only())
def T(serialized, b): script = CScript(x(serialized)) self.assertEqual(script.is_valid(), b)