def verify_interlink(h, hashInterlink, proof): """ returns: mu """ mu = 0 for i, (bit, sibling) in enumerate(proof[::-1]): mu += bit << i assert len(sibling) == 32 if bit: h = Hash(sibling + h) else: h = Hash(h + sibling) assert h == hashInterlink, "root hash did not match" return mu
def calc_state_hash(self): """Calculate a hash representing the state of the database""" def hash_dict(d, *, key_hash_func, value_hash_func): midstate = hashlib.sha256() # sorted() will return the dict items sorted by the has of each key for key_hash, value_hash in sorted( (key_hash_func(key), value_hash_func(value)) for key, value in d.items()): midstate.update(key_hash) midstate.update(value_hash) return midstate.digest() def hash_set(objs, obj_hash_func=lambda obj: obj.hash): obj_hashes = [obj_hash_func(obj) for obj in objs] midstate = hashlib.sha256() for obj_hash in sorted(obj_hashes): midstate.update(obj_hash) return midstate.digest() midstate = hashlib.sha256() colordefs_digest = hash_set(self.colordefs) midstate.update(colordefs_digest) genesis_outpoints_digest = \ hash_dict(self.genesis_outpoints, key_hash_func=lambda outpoint: Hash(outpoint.serialize()), value_hash_func=lambda colordef_set: hash_set(colordef_set)) midstate.update(genesis_outpoints_digest) genesis_scriptPubKeys_digest = \ hash_dict(self.genesis_scriptPubKeys, key_hash_func=lambda scriptPubKey: Hash(scriptPubKey), value_hash_func=lambda colordef_set: hash_set(colordef_set)) midstate.update(genesis_scriptPubKeys_digest) def hash_colorproof_set_by_colordef_dict(d): return hash_dict(d, key_hash_func=lambda colordef: colordef.hash, value_hash_func=lambda colorproof_set: hash_set( colorproof_set)) colored_outpoints_digest = \ hash_dict(self.colored_outpoints, key_hash_func=lambda outpoint: Hash(outpoint.serialize()), value_hash_func=lambda d: hash_colorproof_set_by_colordef_dict(d)) midstate.update(colored_outpoints_digest) return midstate.digest()
def hash_interlink(vInterlink=[]): if len(vInterlink) >= 2: hashL = hash_interlink(vInterlink[: int(len(vInterlink) / 2)]) hashR = hash_interlink(vInterlink[int(len(vInterlink) / 2) :]) return Hash(hashL + hashR) elif len(vInterlink) == 1: return vInterlink[0] else: return b"\x00" * 32
def hash_interlink(vInterlink=[]): if len(vInterlink) >= 2: hashL = hash_interlink(vInterlink[:len(vInterlink) / 2]) hashR = hash_interlink(vInterlink[len(vInterlink) / 2:]) return Hash(hashL + hashR) elif len(vInterlink) == 1: return vInterlink[0] else: return b'\x00' * 32
def set( self, proof, proof_name="", header=None, header_map=None, interlink_map=None, ): """ Registers a proof in the object """ self.proof = proof self.name = proof_name self.headers, self.siblings = self.extract_headers_siblings(self.proof) for i in range(len(self.headers)): self.hashed_headers.append(Hash(self.proof[i][0])) self.size = len(self.proof) ( self.best_level, self.best_score, self.levels, self.scores, ) = best_level_and_score(self.proof) for level in sorted(self.levels.keys()): print("Level", level, "has", self.levels[level], "blocks with score", end="") if level == self.best_level: print(" " + str(self.best_score) + " <- best") else: print(" " + str(self.scores[level])) if header is None or header_map is None or interlink_map is None: print("No interlink provided") return else: print("Interlink provided. Creating isolated proof at level", self.best_level) self.best_level_subproof = isolate_proof_level(self.best_level, proof, header, header_map, interlink_map) ( self.best_level_subproof_headers, self.best_level_subproof_siblings, ) = self.extract_headers_siblings(self.best_level_subproof) self.best_level_subproof_size = len(self.best_level_subproof)
def encode_address(hash160, network): if network == "mainnet": version = 5 elif network == "testnet": version = 196 else: raise ValueError("Unknown network") data = bytes([version]) + hash160 checksum = Hash(data)[0:4] return encode(data + checksum)
def __init__(self, key1: CPubKey, relative_timeout): """ a life signal is a coin that can be spent by key1 immediately or a tmp key after a relative_timeout :param key1: :param relative_timeout: """ self._key1 = key1 self._key2 = CBitcoinSecret.from_secret_bytes( Hash("tmpsecret".encode())) self._relative_timeout = relative_timeout self._life_signal_amount = 0.0001 * COIN
def make_multisig(self, n = None): if n is None: n = random.randrange(0, len(self.keypairs)) secret_bytes = Hash(self.seed + struct.pack('>L', n)) secret_key = CBitcoinSecret.from_secret_bytes(secret_bytes) # 1-of-1 CHECKMULTISIG scriptPubKey's scriptPubKey = CScript([1, secret_key.pub, 1, OP_CHECKMULTISIG]) self.keypairs[scriptPubKey] = secret_key return scriptPubKey
def make_paytopubkeyhash(self, n = None): if n is None: n = random.randrange(0, len(self.keypairs)) secret_bytes = Hash(self.seed + struct.pack('>L', n)) secret_key = CBitcoinSecret.from_secret_bytes(secret_bytes) # pay-to-pubkeyhash scriptPubKey = CScript([OP_DUP, OP_HASH160, Hash160(secret_key.pub), OP_EQUALVERIFY, OP_CHECKSIG]) self.keypairs[scriptPubKey] = secret_key return scriptPubKey
def main(): proxy = bitcoin.rpc.Proxy() assert len(sys.argv) > 1 digests = [] for f in sys.argv[1:]: try: with open(f, 'rb') as fd: digests.append(Hash(fd.read())) except FileNotFoundError as exp: if len(f)/2 in (20, 32): digests.append(x(f)) else: raise exp except IOError as exp: print(exp, file=sys.stderr) continue for digest in digests: unspent = sorted(proxy.listunspent(0), key=lambda _x: hash(_x['amount'])) txins = [CTxIn(unspent[-1]['outpoint'])] value_in = unspent[-1]['amount'] change_addr = proxy.getnewaddress() change_pubkey = proxy.validateaddress(change_addr)['pubkey'] change_out = CMutableTxOut(params.MAX_MONEY, CScript([change_pubkey, OP_CHECKSIG])) digest_outs = [CMutableTxOut(0, CScript([OP_RETURN, digest]))] txouts = [change_out] + digest_outs tx = CMutableTransaction(txins, txouts) FEE_PER_BYTE = 0.00025*COIN/1000 while True: tx.vout[0].nValue = int(value_in - max(len(tx.serialize()) * FEE_PER_BYTE, 0.00011*COIN)) r = proxy.signrawtransaction(tx) assert r['complete'] tx = r['tx'] if value_in - tx.vout[0].nValue >= len(tx.serialize()) * FEE_PER_BYTE: print(b2x(tx.serialize())) print(len(tx.serialize()), 'bytes', file=sys.stderr) print(b2lx(proxy.sendrawtransaction(tx))) break
def spend_preimage(redeem_script, preimages, redeemer_sig, serial_tx): """ Creates a transaction fulfilling the redeem script of the preimage P2SH. Arguements: redeem_script (bytes): The script that specifies the conditions that a tx has to fulfill to transfer funds from the `funding_tx` preimages (list): The preimages that hash into the hash values specified in the `redeem_script` redeemer_sig (bytes): The signature of the redeemer on the `serial_tx` serial_tx (bytes): The serial transaction Returns: The serial raw transaction that passes the script verification """ # Read in transaction temp_tx = CTransaction.deserialize(serial_tx) tx = CMutableTransaction.from_tx(temp_tx) txin = tx.vin[0] # Setup preimages in reverse order script = [] for p in reversed(preimages): script += [p] # Create script sig txin.scriptSig = CScript([redeemer_sig + '\x01'] + script + [redeem_script]) # Verify script redeem_script = CScript(redeem_script) try: VerifyScript(txin.scriptSig, redeem_script.to_p2sh_scriptPubKey(), tx, 0, [SCRIPT_VERIFY_P2SH]) except ValidationError: print("spend_preimage: Script failed to verify") return None serial_tx = tx.serialize() txid = b2lx(Hash(serial_tx)) print("spend_preimage: TXID is %s" % txid) print("spend_preimage: RAW TX is %s" % b2x(serial_tx)) return serial_tx
def spend_escrow(redeem_script, payer_sig, redeemer_sig, serial_tx): """ Creates a transaction fulfilling the redeem script of the escrow P2SH. Arguements: redeem_script (bytes): The script that specifies the conditions that a tx has to fulfill to transfer funds from the `funding_tx` payer_sig (bytes): The signature of the payer on the `serial_tx` redeemer_sig (bytes): The signature of the redeemer on the `serial_tx` serial_tx (bytes): The serial transaction Returns: The serial raw transaction that passes the script verification """ # Read in transaction temp_tx = CTransaction.deserialize(serial_tx) tx = CMutableTransaction.from_tx(temp_tx) txin = tx.vin[0] # Set script sig txin.scriptSig = CScript( [OP_0, payer_sig + '\x01', redeemer_sig + '\x01', redeem_script]) # Verify script redeem_script = CScript(redeem_script) serial_tx = tx.serialize() try: VerifyScript(txin.scriptSig, redeem_script.to_p2sh_scriptPubKey(), tx, 0, [SCRIPT_VERIFY_P2SH]) except ValidationError: print("spend_escrow: Script failed to verify") return None serial_tx = tx.serialize() txid = b2lx(Hash(serial_tx)) print("spend_escrow: TXID is %s" % txid) print("spend_escrow: RAW TX is %s" % b2x(serial_tx)) return serial_tx
CTxIn(unsigned_tx.vin[i].prevout, d.params.spend_redeemScript('exch', exch_seckey, unsigned_tx, i), nSequence=0) for i, d in enumerate(deposits) ] signed_tx = CTransaction(signed_ins, unsigned_tx.vout, unsigned_tx.nLockTime) print(b2x(signed_tx.serialize())) # test script logging.root.setLevel('DEBUG') bitcoin.SelectParams('testnet') user_a_seckey = CBitcoinSecret.from_secret_bytes(Hash(b'alice')) user_b_seckey = CBitcoinSecret.from_secret_bytes(Hash(b'bob')) exch_seckey = CBitcoinSecret.from_secret_bytes(Hash(b'exch')) users = [user_a_seckey, user_b_seckey] params = [] for ukey in users: params.append( DepositParams( user_scriptPubKey=P2PKHBitcoinAddress.from_pubkey( ukey.pub).to_scriptPubKey(), exch_scriptPubkey=P2PKHBitcoinAddress.from_pubkey( exch_seckey.pub).to_scriptPubKey(), locktime=1000000, # block 1 million
def dummy_user(name: str): secret = CBitcoinSecret.from_secret_bytes(Hash(name.encode())) return secret, Party(name, secret.pub)
import socket import time from typing import Iterable from bitcoin import SelectParams from bitcoin.core import Hash, b2lx from bitcoin.messages import * from bitcoin.net import CInv, CAddress from ipsiblings.model import JustExit USE_TESTNET = True PORT = 18333 if USE_TESTNET else 8333 if USE_TESTNET: SelectParams('testnet') FAKE_TX_HASH = Hash("not your usual tx".encode('utf-8')) INV_SEND_TS = -1 g_getaddr_send_ts = -1 RUN_ID = int(random.uniform(0, 65535)) g_ver_ts = 0 print(f'run id is {RUN_ID}') def version_pkt(client_ip, server_ip, nonce): msg = msg_version() msg.nVersion = 70002 msg.addrTo.ip = server_ip msg.addrTo.port = PORT msg.addrFrom.ip = client_ip msg.addrFrom.port = PORT # msg.nServices = 1 # the default, but important, otherwise they don't want our ADDRs
sys.exit(1) from hashlib import sha256 from enum import Enum from bitcoin import SelectParams from bitcoin.core import b2x, b2lx, x, Hash160, Hash from bitcoin.core.script import CScript, OP_HASH160, OP_EQUAL, OP_CHECKSIG, OP_EQUALVERIFY, OP_DUP, OP_0 from bitcoin.wallet import CBitcoinAddress, CBitcoinSecret from bitcoin.rpc import Proxy SelectParams('testnet') proxy = Proxy() # Not recognized when datadir conf param is present Sha256 = lambda x: sha256(x).digest() Hash256 = lambda x: Hash(x) def patch(asm): full = asm asm = '' for i in full: if i == "" or i == "0": i = '0P_0' if i == 'OP_NOP1': i = 'OP_DESERIALIZE' asm += i + ' ' return asm.strip() def pp(asm): pp = "" rtn = '\n'