def templateReplaceOne(s, Jorig): # FIXME: This is kind of ugly code.. match = re.match(r"\<bitcoin-address\:([a-z]+)\>", s) if match: res = bitcoin.privtoaddr(bitcoin.sha256(match.group(1))) #logging.info("Replace %s with %s" % (match.group(0), res)) return res match = re.match(r"\<hash-of\:([^>]+)\>", s) if match: fn = match.group(1) res = bitcoin.sha256(open(fn).read()) #logging.info("Replace %s with %s" % (match.group(0), res)) return res match = re.match(r"\<signature:([a-z]+)\>", s) if match: msg = "VOTE-FORMAT-VERSION-1 %s %s %s %s %s" % ( templateReplaceOne(Jorig["handle"], Jorig), templateReplaceOne(Jorig["addr"], Jorig), templateReplaceOne(Jorig["ballot_option"], Jorig), templateReplaceOne(Jorig["proposal"], Jorig), templateReplaceOne(Jorig["proposal_meta"], Jorig)) privkey = bitcoin.sha256(match.group(1)) res = bitcoin.ecdsa_sign(msg, privkey) #logging.info("Replace %s with %s" % (match.group(0), res)) return res else: return s
def templateReplaceOne(s, Jorig): # FIXME: This is kind of ugly code.. match=re.match(r"\<bitcoin-address\:([a-z]+)\>", s) if match: res=bitcoin.privtoaddr( bitcoin.sha256(match.group(1))) #logging.info("Replace %s with %s" % (match.group(0), res)) return res match=re.match(r"\<hash-of\:([^>]+)\>", s) if match: fn=match.group(1) res=bitcoin.sha256(open(fn).read()) #logging.info("Replace %s with %s" % (match.group(0), res)) return res match=re.match(r"\<signature:([a-z]+)\>", s) if match: msg="VOTE-FORMAT-VERSION-1 %s %s %s %s %s" % ( templateReplaceOne(Jorig["handle"], Jorig), templateReplaceOne(Jorig["addr"], Jorig), templateReplaceOne(Jorig["ballot_option"], Jorig), templateReplaceOne(Jorig["proposal"], Jorig), templateReplaceOne(Jorig["proposal_meta"], Jorig) ) privkey=bitcoin.sha256(match.group(1)) res=bitcoin.ecdsa_sign(msg, privkey) #logging.info("Replace %s with %s" % (match.group(0), res)) return res else: return s
def test_ecrecover(self): priv = b.sha256('some big long brainwallet password') pub = b.privtopub(priv) msghash = b.sha256('the quick brown fox jumps over the lazy dog') V, R, S = b.ecdsa_raw_sign(msghash, priv) assert b.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.sha3(b.encode_pubkey(pub, 'bin')[1:])[12:] assert utils.privtoaddr(priv) == addr result = self.c.test_ecrecover(utils.big_endian_to_int(msghash.decode('hex')), V, R, S) assert result == utils.big_endian_to_int(addr)
def test_ecrecover(self): priv = b.sha256('some big long brainwallet password') pub = b.privtopub(priv) msghash = b.sha256('the quick brown fox jumps over the lazy dog') V, R, S = b.ecdsa_raw_sign(msghash, priv) assert b.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.sha3(b.encode_pubkey(pub, 'bin')[1:])[12:] assert utils.privtoaddr(priv) == addr result = self.c.test_ecrecover( utils.big_endian_to_int(msghash.decode('hex')), V, R, S) assert result == utils.big_endian_to_int(addr)
def generate_mcaf(currencies, seed, mode="P"): priv = sha256(seed) pub = privtopub(priv) #import ipdb; ipdb.set_trace() hash160 = binascii.hexlify(bin_hash160(binascii.unhexlify(pub))) print(hash160, b58encode(hash160)) if mode == 'P': address = "P%s0%s" % (encode_currency_support_token(currencies).decode( "utf-8"), b58encode(hash160).decode("utf-8")) else: raise NotImplementedError("Only P mode implemented") return "%s%s" % (address, sha256(address)[:4])
def sign_n_send(filename, priv, addr, fee): if not os.path.isfile(filename): print "ERR: file not found" print "exiting, no operation" exit(-1) balance = get_balance(addr) if balance < fee: print "ERR: not enough funds, refill wallet", addr exit(-1) f = open(filename, "r") content = f.read() hashed = btc.sha256(content) print "hash\n" print hashed print "" sig_tx = op_return_tx('sha256:' + hashed[:32], priv) print "transaction hex is\n" print sig_tx #raise(Exception('not finished')) tid = btc.pushtx(sig_tx, 'testnet', source='blockr') return tid
def comprovaHash(msg): msg_hash=b.sha256(msg) print(msg_hash+" -- "+msg) if msg_hash[0:4] == "0000": return True else: return False
def generate_keypair(crypto, seed, password=None): """ Generate a private key and publickey for any currency, given a seed. That seed can be random, or a brainwallet phrase. """ pub_byte, priv_byte = get_magic_bytes(crypto) priv = sha256(seed) pub = privtopub(priv) priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte) if password: # pycrypto etc. must be installed or this will raise ImportError, hence inline import. from .bip38 import Bip38EncryptedPrivateKey priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password)) compressed_pub = encode_pubkey(pub, 'hex_compressed') ret = { 'public': { 'hex_uncompressed': pub, 'hex': compressed_pub, 'address': pubtoaddr(compressed_pub, pub_byte) }, 'private': { 'wif': priv_wif } } if not password: # only these are valid when no bip38 password is supplied ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte) ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte) ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte) return ret
def test_external_commitments(setup_podle): """Add this generated commitment to the external list {txid:N:{'P':pubkey, 'reveal':{1:{'P2':P2,'s':s,'e':e}, 2:{..},..}}} Note we do this *after* the sendpayment test so that the external commitments will not erroneously used (they are fake). """ ecs = {} tries = jm_single().config.getint("POLICY","taker_utxo_retries") for i in range(10): priv = os.urandom(32) dummy_utxo = btc.sha256(priv)+":2" ecs[dummy_utxo] = {} ecs[dummy_utxo]['reveal']={} for j in range(tries): P, P2, s, e, commit = generate_single_podle_sig(priv, j) if 'P' not in ecs[dummy_utxo]: ecs[dummy_utxo]['P']=P ecs[dummy_utxo]['reveal'][j] = {'P2':P2, 's':s, 'e':e} btc.add_external_commitments(ecs) used, external = btc.get_podle_commitments() for u in external: assert external[u]['P'] == ecs[u]['P'] for i in range(tries): for x in ['P2', 's', 'e']: assert external[u]['reveal'][str(i)][x] == ecs[u]['reveal'][i][x]
def create_keychain(self): """ The guid generation can take a while. While it's doing that we will open a port to allow a UI to connect and listen for generation to complete. """ print "Generating GUID, this may take a few minutes..." d = Deferred() api = GUIDGenerationListener(d) site = Site(api, timeout=None) connector = reactor.listenTCP(18470, site, interface="127.0.0.1") start = time.time() g = GUID() d.callback((round(time.time() - start, 2), connector)) self.guid = g.guid self.guid_privkey = g.privkey self.signing_key = nacl.signing.SigningKey(self.guid_privkey) self.guid_signed_pubkey = g.signed_pubkey self.db.set_key("guid", self.guid_privkey, self.guid_signed_pubkey) self.bitcoin_master_privkey = bitcoin.bip32_master_key( bitcoin.sha256(self.guid_privkey)) self.bitcoin_master_pubkey = bitcoin.bip32_privtopub( self.bitcoin_master_privkey) self.db.set_key("bitcoin", self.bitcoin_master_privkey, self.bitcoin_master_pubkey) self.encryption_key = PrivateKey(self.guid_privkey) self.encryption_pubkey = self.encryption_key.public_key.encode()
def generatekey(): keyword = request.args.get('keyword') mypriv = bitcoin.sha256(keyword) mypubl = bitcoin.privkey_to_pubkey(mypriv) myaddress = bitcoin.pubkey_to_address(mypubl) myInfo = {'mypriv': mypriv, 'mypubl': mypubl, 'myaddress': myaddress} return json.dumps(myInfo)
def test_cccoin_mc_write(mc_node_url, cccoin_core): cccoin_core.mcq = MediachainQueue(mc_api_url=mc_node_url, default_namespace='cccoin') the_pw = 'some big long brainwallet password' priv = btc.sha256(the_pw) pub = btc.privtopub(priv) blind_post, unblind_post = client_post( 'http://foo', 'The Title ', priv, pub, ) cccoin_core.submit_blind_action(blind_post) cccoin_core.submit_unblind_action(unblind_post) cccoin_core.cw.loop_once() start_block = cccoin_core.cw.latest_block_num while cccoin_core.cw.latest_block_num < start_block + 3: # not sure why / if this is the magic number, but it WFM... cccoin_core.cw.loop_once() sleep(0.1) cccoin_core.mcq.wait_for_completion() client = MediachainClient(mc_api_url=mc_node_url) results = IOLoop.current().run_sync( lambda: client.query('SELECT * FROM cccoin')) assert (len(results) > 0)
def generate_keypair(crypto, seed, password=None): """ Generate a private key and publickey for any currency, given a seed. That seed can be random, or a brainwallet phrase. """ pub_byte, priv_byte = get_magic_bytes(crypto) priv = sha256(seed) pub = privtopub(priv) if priv_byte >= 128: priv_byte -= 128 #pybitcointools bug priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte) if password: priv_wif = bip38_encrypt(priv_wif, password) compressed_pub = encode_pubkey(pub, 'hex_compressed') ret = { 'public': { 'hex_uncompressed': pub, 'hex': compressed_pub, 'address': pubtoaddr(compressed_pub, pub_byte) }, 'private': { 'wif': priv_wif } } if not password: # only these are valid when no bip38 password is supplied ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte) ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte) ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte) return ret
def can_spent(self): for input in self.inputs: print(input) print(input.hash) if not bitcoin.ecdsa_verify(bitcoin.sha256(str(input)), input.sign, input.pubk): raise Exception()
def makeTestAction(author, apart, pgp=False): """ Create signed test action where privkey of author equals sha256(author). """ action_string = config.action_prefix + apart privkey = bitcoin.sha256(author.name) if pgp: # use PGP signature assert author.name in ["member_a", "member_b"] gpg = gpglayer.gpgInstance() ki1 = gpg.import_keys(testkeys.privkey1) ki2 = gpg.import_keys(testkeys.privkey2) signature = gpg.sign(action_string, keyid=(ki1.fingerprints[0] if author.name == "member_a" else ki2.fingerprints[0]), detach=True, passphrase="123").data.decode("ascii") assert len(signature) else: signature = bitcoin.ecdsa_sign(action_string, privkey) return Action(author=author, action_string=action_string, signature=signature)
def serve_submit_vote(): handle=request.POST["handle"] addr=request.POST["addr"] ballot_option=request.POST["ballot_option"] proposal_hash=request.POST["proposal_hash"] proposal_meta_hash=request.POST["proposal_meta_hash"] signature=request.POST["signature"] j={ "type" : "Vote", "version" : 1, "handle" : handle, "addr" : addr, "ballot_option" : ballot_option, "proposal" : proposal_hash, "proposal_meta" : proposal_meta_hash, "signature" : signature } js=json_pretty(j) sha256=bitcoin.sha256(js) outf="incoming/%s-vote.json" % sha256 with open(outf, "w") as f: f.write(js) try: vote=Vote.fromJSON(js, outf, False) except InvalidSignatureError, e: abort(404, "Vote has invalid signature.")
def read(self, url): self.url = url u = urlparse.urlparse(url) self.domain = u.netloc try: connection = httplib.HTTPConnection( u.netloc) if u.scheme == 'http' else httplib.HTTPSConnection( u.netloc) connection.request("GET", u.geturl(), headers=REQUEST_HEADERS) response = connection.getresponse() except: self.error = "cannot read url" return try: r = response.read() except: self.error = "cannot read" return self.id = bitcoin.sha256(r)[0:16].encode('hex') filename = os.path.join(self.dir_path, self.id) with open(filename, 'w') as f: f.write(r) return self.parse(r)
def create_keychain(self): """ The guid generation can take a while. While it's doing that we will open a port to allow a UI to connect and listen for generation to complete. """ print "Generating GUID, this may take a few minutes..." d = Deferred() api = GUIDGenerationListener(d) site = Site(api, timeout=None) connector = reactor.listenTCP(18470, site, interface="127.0.0.1") start = time.time() g = GUID() d.callback((round(time.time() - start, 2), connector)) self.guid = g.guid self.guid_privkey = g.privkey self.signing_key = nacl.signing.SigningKey(self.guid_privkey) self.guid_signed_pubkey = g.signed_pubkey self.db.set_key("guid", self.guid_privkey, self.guid_signed_pubkey) self.bitcoin_master_privkey = bitcoin.bip32_master_key(bitcoin.sha256(self.guid_privkey)) self.bitcoin_master_pubkey = bitcoin.bip32_privtopub(self.bitcoin_master_privkey) self.db.set_key("bitcoin", self.bitcoin_master_privkey, self.bitcoin_master_pubkey) self.encryption_key = PrivateKey(self.guid_privkey) self.encryption_pubkey = self.encryption_key.public_key.encode()
def test_external_commitments(setup_podle): """Add this generated commitment to the external list {txid:N:{'P':pubkey, 'reveal':{1:{'P2':P2,'s':s,'e':e}, 2:{..},..}}} Note we do this *after* the sendpayment test so that the external commitments will not erroneously used (they are fake). """ ecs = {} tries = jm_single().config.getint("POLICY", "taker_utxo_retries") for i in range(10): priv = os.urandom(32) dummy_utxo = btc.sha256(priv) + ":2" ecs[dummy_utxo] = {} ecs[dummy_utxo]['reveal'] = {} for j in range(tries): P, P2, s, e, commit = generate_single_podle_sig(priv, j) if 'P' not in ecs[dummy_utxo]: ecs[dummy_utxo]['P'] = P ecs[dummy_utxo]['reveal'][j] = {'P2': P2, 's': s, 'e': e} btc.add_external_commitments(ecs) used, external = btc.get_podle_commitments() for u in external: assert external[u]['P'] == ecs[u]['P'] for i in range(tries): for x in ['P2', 's', 'e']: assert external[u]['reveal'][str( i)][x] == ecs[u]['reveal'][i][x]
def read_file(self, key): filename = os.path.join(self.dir_path, key) with open(filename, 'r') as f: r = f.read() assert key == bitcoin.sha256(r)[0:16].encode('hex') self.id = key self.parse(r)
def generate_mcaf(currencies, seed, mode="P"): priv = sha256(seed) pub = privtopub(priv) #import ipdb; ipdb.set_trace() hash160 = binascii.hexlify(bin_hash160(binascii.unhexlify(pub))) print(hash160, b58encode(hash160)) if mode == 'P': address = "P%s0%s" % ( encode_currency_support_token(currencies).decode("utf-8"), b58encode(hash160).decode("utf-8") ) else: raise NotImplementedError("Only P mode implemented") return "%s%s" % (address, sha256(address)[:4])
def _get_wallet_sha256(): for i in w: HEX=btc.encode_privkey(btc.sha256(str(i)),"hex") addr=btc.privtoaddr(HEX) if(addr==match): print(WIF) else: print(addr)
def controller_recover_key(recovery_phrase): #function to recover a public and private key pair from a mnemonic phrase mnemonic_base = Mnemonic(language='english') seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey
def sign_db(self, privkey, index): #function to add a signature to the mapping object generated from the supplied key jsonstring = json.dumps(self.map["assets"], sort_keys=True) jsonstring += str(self.map["n"]) + str(self.map["m"]) + str( self.map["time"]) + str(self.map["height"]) strhash = bc.sha256(jsonstring) sig = bc.ecdsa_sign(jsonstring, privkey) self.map["sigs"][index] = sig
def read_file(self, key): filename = os.path.join(self.dir_path, key) with open(filename, "r") as f: r = f.read() assert key == bitcoin.sha256(r)[0:16].encode("hex") self.id = key self.parse(r)
def hash_list(l): def g(x): if type(x) in [int, long]: x=utils.int_to_big_endian(x) return x y=map(g, l) y=[utils.zpad(x, 32) for x in y] y=''.join(y) #save for pretty print z="".join("{:02x}".format(ord(c)) for c in y) return b.sha256(y)
def test_invalid1(bare_session, member_list, member_a): privkey = bitcoin.sha256("invalid") multi_action_string = mas1(member_list) multi_signature = bitcoin.ecdsa_sign(multi_action_string, privkey) with pytest.raises(ValidationError): ma = MultiAction(member_a, multi_action_string, multi_signature)
def generate_single_podle_sig(priv, i): """Make a podle entry for key priv at index i, using a dummy utxo value. This calls the underlying 'raw' code based on the class PoDLE, not the library 'generate_podle' which intelligently searches and updates commitments. """ dummy_utxo = btc.sha256(priv) + ":3" podle = btc.PoDLE(dummy_utxo, binascii.hexlify(priv)) r = podle.generate_podle(i) return (r['P'], r['P2'], r['sig'], r['e'], r['commit'])
def create_pair(b58_magic_byte, address_magic_byte, seed=None): """Function create private key and address""" if seed is None: seed = KeyGenerator.random_seed() hash = sha256(seed) private_key = int(hash, base=16) private_key_wif = bin_to_b58check(encode(private_key, 256, 32), b58_magic_byte) address = privkey_to_address(private_key, address_magic_byte) return private_key_wif, address
def hash_list(l): def g(x): if type(x) in [int, long]: x = utils.int_to_big_endian(x) return x y = map(g, l) y = [utils.zpad(x, 32) for x in y] y = ''.join(y) #save for pretty print z="".join("{:02x}".format(ord(c)) for c in y) return b.sha256(y)
def test_construct1(bare_session, member_list, member_a): privkey = bitcoin.sha256(member_a.name) multi_action_string = mas1(member_list) multi_signature = bitcoin.ecdsa_sign(multi_action_string, privkey) ma = MultiAction(member_a, multi_action_string, multi_signature) assert len(ma.actions) == 3
def sign(self, priv): # tx_in들에 sign에 self.hash에 대한 서명을 작성 for tx_in in self.inputs: # digest = SHA256.new(str(tx_in).encode()) # signer = PKCS1_v1_5.new(priv) # tx_in.sign = signer.sign(digest) # 서명 # tx_in.pubk = str(priv.publickey()) tx_in.pubk = bitcoin.privkey_to_pubkey(priv) digest = bitcoin.sha256(str(tx_in)) tx_in.sign = bitcoin.ecdsa_sign(digest, priv)
def test_commitment_retries(setup_podle): """Assumes no external commitments available. Generate pretend priv/utxo pairs and check that they can be used taker_utxo_retries times. """ allowed = jm_single().config.getint("POLICY", "taker_utxo_retries") #make some pretend commitments dummy_priv_utxo_pairs = [(btc.sha256(os.urandom(10)), btc.sha256(os.urandom(10))+":0") for _ in range(10)] #test a single commitment request of all 10 for x in dummy_priv_utxo_pairs: p = btc.generate_podle([x], allowed) assert p #At this point slot 0 has been taken by all 10. for i in range(allowed-1): p = btc.generate_podle(dummy_priv_utxo_pairs[:1], allowed) assert p p = btc.generate_podle(dummy_priv_utxo_pairs[:1], allowed) assert p is None
def test_commitment_retries(setup_podle): """Assumes no external commitments available. Generate pretend priv/utxo pairs and check that they can be used taker_utxo_retries times. """ allowed = jm_single().config.getint("POLICY", "taker_utxo_retries") #make some pretend commitments dummy_priv_utxo_pairs = [(btc.sha256(os.urandom(10)), btc.sha256(os.urandom(10)) + ":0") for _ in range(10)] #test a single commitment request of all 10 for x in dummy_priv_utxo_pairs: p = btc.generate_podle([x], allowed) assert p #At this point slot 0 has been taken by all 10. for i in range(allowed - 1): p = btc.generate_podle(dummy_priv_utxo_pairs[:1], allowed) assert p p = btc.generate_podle(dummy_priv_utxo_pairs[:1], allowed) assert p is None
def makeTestMultiAction(author, aparts): """ Create signed multi action with privkey of authors as for makeTestAction. """ multi_action_string = config.action_prefix + ( "\n@@@@@\n" + config.action_prefix).join(aparts) privkey = bitcoin.sha256(author.name) multi_signature = bitcoin.ecdsa_sign(multi_action_string, privkey) return MultiAction(author=author, multi_action_string=multi_action_string, multi_signature=multi_signature)
def makeTestMemberKeys(): member_names = ["member_%s" % x for x in "abcdefghijklmnopqrstuvwxyz"] privkeys = [ bitcoin.hex_to_b58check(bitcoin.sha256(member), 0x80) for member in member_names ] addresses = [bitcoin.privkey_to_address(priv) for priv in privkeys] return member_names, addresses, privkeys
def __init__(self, file_name): """ Initializes the following field: file_name: The file name string of this object on disk (or None). sha256: If a file name is given, this is the SHA256 of this object, as a hex string. """ self.file_name = file_name if self.file_name: self.sha256 = bitcoin.sha256(open(file_name).read()) self.hash_refs = [] self.hashlist_refs = []
def __init__(self, file_name): """ Initializes the following field: file_name: The file name string of this object on disk (or None). sha256: If a file name is given, this is the SHA256 of this object, as a hex string. """ self.file_name=file_name if self.file_name: self.sha256=bitcoin.sha256(open(file_name).read()) self.hash_refs=[] self.hashlist_refs=[]
def test_invalid_newml(bare_session, member_list, member_a): newml = makeTestMemberList(Global.current_member_list()) Global.set_current_member_list(newml) # invalid action string (not current member list) action_string = config.action_prefix+member_list.hashref() privkey = bitcoin.sha256(member_a.name) signature = bitcoin.ecdsa_sign(action_string, privkey) with pytest.raises(ValidationError): Action(member_a, action_string, signature)
def get_conn_id(self): """ Returns identifier of this connection, built on attributes that uniquely characteraize the connection. :return: """ if self.__use_ssh_tunnel: id = 'SSH:' + self.ssh_conn_cfg.host + ':' + self.__host + ':' + self.__port else: id = 'DIRECT:' + self.__host id = bitcoin.sha256(id) return id
def donation_address(reusable_donation_pubkey=None): if not reusable_donation_pubkey: reusable_donation_pubkey = ('02be838257fbfddabaea03afbb9f16e852' '9dfe2de921260a5c46036d97b5eacf2a') sign_k = binascii.hexlify(os.urandom(32)) c = btc.sha256(btc.multiply(sign_k, reusable_donation_pubkey, True)) sender_pubkey = btc.add_pubkeys([reusable_donation_pubkey, btc.privtopub(c+'01', True)], True) sender_address = btc.pubtoaddr(sender_pubkey, get_p2pk_vbyte()) log.info('sending coins to ' + sender_address) return sender_address, sign_k
def controller_keygen(): #function to generate a random mnemonic recovery phrase #and in turn a private a public keys decode_hex = codecs.getdecoder("hex_codec") entropy_hex = bc.random_key() entropy_bytes = decode_hex(entropy_hex)[0] mnemonic_base = Mnemonic(language='english') recovery_phrase = mnemonic_base.to_mnemonic(entropy_bytes) seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey, recovery_phrase
def donation_address(cjtx, wallet): privkey = wallet.get_key_from_addr(wallet.get_new_addr(0,0)) reusable_donation_pubkey = '02be838257fbfddabaea03afbb9f16e8529dfe2de921260a5c46036d97b5eacf2a' global sign_k import os import binascii sign_k = os.urandom(32) log.debug("Using the following nonce value: "+binascii.hexlify(sign_k)) c = btc.sha256(btc.multiply(binascii.hexlify(sign_k), reusable_donation_pubkey, True)) sender_pubkey = btc.add_pubkeys([reusable_donation_pubkey, btc.privtopub(c+'01', True)], True) sender_address = btc.pubtoaddr(sender_pubkey, get_p2pk_vbyte()) log.debug('sending coins to ' + sender_address) return privkey, sender_address
def create_keychain(self): print "Generating GUID, stand by..." g = GUID() self.guid = g.guid self.guid_privkey = g.privkey self.signing_key = nacl.signing.SigningKey(self.guid_privkey) self.guid_signed_pubkey = g.signed_pubkey self.db.set_key("guid", self.guid_privkey, self.guid_signed_pubkey) self.bitcoin_master_privkey = bitcoin.bip32_master_key(bitcoin.sha256(self.guid_privkey)) self.bitcoin_master_pubkey = bitcoin.bip32_privtopub(self.bitcoin_master_privkey) self.db.set_key("bitcoin", self.bitcoin_master_privkey, self.bitcoin_master_pubkey) self.encryption_key = PrivateKey(self.guid_privkey) self.encryption_pubkey = self.encryption_key.public_key.encode()
def parse(self, r): self.id = bitcoin.sha256(r)[0:16].encode('hex') try: self.data = pb2.PaymentRequest() self.data.ParseFromString(r) except: self.error = "cannot parse payment request" return self.details = pb2.PaymentDetails() self.details.ParseFromString(self.data.serialized_payment_details) self.outputs = [] for o in self.details.outputs: addr = transaction.get_address_from_output_script(o.script)[1] self.outputs.append(('address', addr, o.amount)) self.memo = self.details.memo self.payment_url = self.details.payment_url
def donation_address(tx, wallet): from bitcoin.main import multiply, G, deterministic_generate_k, add_pubkeys reusable_donation_pubkey = ('02be838257fbfddabaea03afbb9f16e852' '9dfe2de921260a5c46036d97b5eacf2a') privkey = wallet.get_key_from_addr(wallet.get_new_addr(0,0)) msghash = btc.bin_txhash(tx, btc.SIGHASH_ALL) # generate unpredictable k global sign_k sign_k = deterministic_generate_k(msghash, privkey) c = btc.sha256(multiply(reusable_donation_pubkey, sign_k)) sender_pubkey = add_pubkeys( reusable_donation_pubkey, multiply( G, c)) sender_address = btc.pubtoaddr(sender_pubkey, get_p2pk_vbyte()) log.debug('sending coins to ' + sender_address) return privkey, sender_address
def tx_response(self, response): params, result = self.parse_response(response) if not params: return tx_hash, tx_height = params assert tx_hash == hash_encode(sha256(result.decode('hex'))) tx = Transaction(result) try: tx.deserialize() except Exception: self.print_msg("cannot deserialize transaction, skipping", tx_hash) return self.wallet.receive_tx_callback(tx_hash, tx, tx_height) self.requested_tx.remove((tx_hash, tx_height)) self.print_error("received tx:", tx_hash, len(tx.raw)) # callbacks self.network.trigger_callback('new_transaction', (tx,)) if not self.requested_tx: self.network.trigger_callback('updated')
def donation_address(cjtx): reusable_donation_pubkey = '02be838257fbfddabaea03afbb9f16e8529dfe2de921260a5c46036d97b5eacf2a' donation_utxo_data = cjtx.input_utxos.iteritems().next() global donation_utxo donation_utxo = donation_utxo_data[0] privkey = cjtx.wallet.get_key_from_addr(donation_utxo_data[1]['address']) tx = btc.mktx(cjtx.utxo_tx, cjtx.outputs) #tx without our inputs and outputs #address = privtoaddr(privkey) #signing_tx = signature_form(tx, 0, mk_pubkey_script(address), SIGHASH_ALL) msghash = btc.bin_txhash(tx, btc.SIGHASH_ALL) #generate unpredictable k global sign_k sign_k = btc.deterministic_generate_k(msghash, privkey) c = btc.sha256(btc.multiply(reusable_donation_pubkey, sign_k)) sender_pubkey = btc.add_pubkeys(reusable_donation_pubkey, btc.multiply(btc.G, c)) sender_address = btc.pubtoaddr(sender_pubkey, get_p2pk_vbyte()) debug('sending coins to ' + sender_address) return sender_address
def decode_mcaf(address): if not address.startswith("P"): raise NotImplementedError("Only P mode implemented at this time") address = address.replace("O", "0") if not sha256(address[:-4]) == address[-4:]: raise Exception("Invalid checksum") token, payload = address.split("0") currencies = decode_currency_support_token(token[1:]) ret = {} for currency in currencies: try: ret[currency] = change_version_byte( payload, to_crypto=currency ) except CurrencyNotSupported as exc: ret[currency] = str(exc) return ret
def donation_address(cjtx): from bitcoin.main import multiply, G, deterministic_generate_k, add_pubkeys reusable_donation_pubkey = ('02be838257fbfddabaea03afbb9f16e852' '9dfe2de921260a5c46036d97b5eacf2a') donation_utxo_data = cjtx.input_utxos.iteritems().next() global donation_utxo donation_utxo = donation_utxo_data[0] privkey = cjtx.wallet.get_key_from_addr(donation_utxo_data[1]['address']) # tx without our inputs and outputs tx = btc.mktx(cjtx.utxo_tx, cjtx.outputs) msghash = btc.bin_txhash(tx, btc.SIGHASH_ALL) # generate unpredictable k global sign_k sign_k = deterministic_generate_k(msghash, privkey) c = btc.sha256(multiply(reusable_donation_pubkey, sign_k)) sender_pubkey = add_pubkeys( reusable_donation_pubkey, multiply( G, c)) sender_address = btc.pubtoaddr(sender_pubkey, get_p2pk_vbyte()) log.debug('sending coins to ' + sender_address) return sender_address
def main(): from socket import gethostname nickname = 'cj-maker-' + btc.sha256(gethostname())[:6] import sys seed = sys.argv[1] #btc.sha256('dont use brainwallets except for holding testnet coins') common.load_program_config() wallet = Wallet(seed, max_mix_depth=5) common.bc_interface.sync_wallet(wallet) from irc import IRCMessageChannel irc = IRCMessageChannel(nickname) maker = Maker(irc, wallet) try: print 'connecting to irc' irc.run() except: debug('CRASHING, DUMPING EVERYTHING') debug('wallet seed = ' + seed) debug_dump_object(wallet, ['addr_cache']) debug_dump_object(maker) import traceback traceback.print_exc()
def read(self, url): self.url = url u = urlparse.urlparse(url) self.domain = u.netloc try: connection = httplib.HTTPConnection(u.netloc) if u.scheme == "http" else httplib.HTTPSConnection(u.netloc) connection.request("GET", u.geturl(), headers=REQUEST_HEADERS) response = connection.getresponse() except: self.error = "cannot read url" return try: r = response.read() except: self.error = "cannot read" return self.id = bitcoin.sha256(r)[0:16].encode("hex") filename = os.path.join(self.dir_path, self.id) with open(filename, "w") as f: f.write(r) return self.parse(r)
p = subprocess.Popen([ELECTRUM_BIN,'daemon','start']) if p.wait() != 0: print 'Error: electrum daemon not started...' sys.exit(-1) text = 'File(s) to be hashed by sha256*:\n' bytes = 0 data = '' for each_file in files_to_stamp: # binary read option to make it platform independent file2hash = open(each_file,'rb') data += file2hash.read() file2hash.close() sha256file=bitcoin.sha256(data) bytes+=len(data) data = sha256file text += each_file+' '+sha256file+'\n' if not quiet: sys.stdout.write(text) if stamp: logfile.write(text) data = sha256file text = '' sha2564files = data if burn: payto_addr = bitcoin.pubtoaddr(sha2564files)
def new_wallet_mnemonic(brainwallet): a=b.sha256(brainwallet) return new_wallet(a)
def get_bytes(self, n): while len(self.pool) < n: self.pool.extend(self.sha) self.sha = sha256(self.sha) result, self.pool = self.pool[:n], self.pool[n:] return result
def __init__(self, seed): self.sha = sha256(seed) self.pool = bytearray()
def test_donation_address(setup_donations, amount): wallets = make_wallets(1, wallet_structures=[[1,1,1,0,0]], mean_amt=0.5) wallet = wallets[0]['wallet'] jm_single().bc_interface.sync_wallet(wallet) #make a rdp from a simple privkey rdp_priv = "\x01"*32 reusable_donation_pubkey = binascii.hexlify(secp256k1.PrivateKey( privkey=rdp_priv, raw=True, ctx=btc.ctx).pubkey.serialize()) dest_addr, sign_k = donation_address(reusable_donation_pubkey) print dest_addr jm_single().bc_interface.rpc('importaddress', [dest_addr, '', False]) ins_full = wallet.unspent total = sum(x['value'] for x in ins_full.values()) ins = ins_full.keys() output_addr = wallet.get_new_addr(1, 1) fee_est = 10000 outs = [{'value': amount, 'address': dest_addr}, {'value': total - amount - fee_est, 'address': output_addr}] tx = btc.mktx(ins, outs) de_tx = btc.deserialize(tx) for index, ins in enumerate(de_tx['ins']): utxo = ins['outpoint']['hash'] + ':' + str(ins['outpoint']['index']) addr = ins_full[utxo]['address'] priv = wallet.get_key_from_addr(addr) priv = binascii.unhexlify(priv) usenonce = binascii.unhexlify(sign_k) if index == 0 else None if index == 0: log.debug("Applying rdp to input: " + str(ins)) tx = btc.sign(tx, index, priv, usenonce=usenonce) #pushtx returns False on any error push_succeed = jm_single().bc_interface.pushtx(tx) if push_succeed: log.debug(btc.txhash(tx)) else: assert False #Role of receiver: regenerate the destination private key, #and address, from the nonce of the first input; check it has #received the coins. detx = btc.deserialize(tx) first_utxo_script = detx['ins'][0]['script'] sig, pub = btc.deserialize_script(first_utxo_script) log.debug(sig) sig = binascii.unhexlify(sig) kGlen = ord(sig[3]) kG = sig[4:4+kGlen] log.debug(binascii.hexlify(kG)) if kG[0] == "\x00": kG = kG[1:] #H(rdp private key * K) + rdp should be ==> dest addr #Open issue: re-introduce recovery without ECC shenanigans #Just cheat by trying both signs for pubkey coerced_kG_1 = "02" + binascii.hexlify(kG) coerced_kG_2 = "03" + binascii.hexlify(kG) for coerc in [coerced_kG_1, coerced_kG_2]: c = btc.sha256(btc.multiply(binascii.hexlify(rdp_priv), coerc, True)) pub_check = btc.add_pubkeys([reusable_donation_pubkey, btc.privtopub(c+'01', True)], True) addr_check = btc.pubtoaddr(pub_check, get_p2pk_vbyte()) log.debug("Found checked address: " + addr_check) if addr_check == dest_addr: time.sleep(3) received = jm_single().bc_interface.get_received_by_addr( [dest_addr], None)['data'][0]['balance'] assert received == amount return assert False
balance = 0.0 for addrvalue in wallet.unspent.values(): if addr == addrvalue["address"]: balance += addrvalue["value"] used = " used" if balance > 0.0 else "empty" balance_depth += balance wip_privkey = ( btc.encode_privkey(privkey, "wif_compressed", get_p2pk_vbyte()) if options.showprivkey else "" ) cus_print(" " * 13 + "%-35s%s %.8f btc %s" % (addr, used, balance / 1e8, wip_privkey)) total_balance += balance_depth print("for mixdepth=%d balance=%.8fbtc" % (m, balance_depth / 1e8)) print("total balance = %.8fbtc" % (total_balance / 1e8)) elif method == "generate" or method == "recover": if method == "generate": seed = btc.sha256(os.urandom(64))[:32] words = mn_encode(seed) print("Write down this wallet recovery seed\n\n" + " ".join(words) + "\n") elif method == "recover": words = raw_input("Input 12 word recovery seed: ") words = words.split() # default for split is 1 or more whitespace chars if len(words) != 12: print("ERROR: Recovery seed phrase must be exactly 12 words.") sys.exit(0) seed = mn_decode(words) print(seed) password = getpass.getpass("Enter wallet encryption passphrase: ") password2 = getpass.getpass("Reenter wallet encryption passphrase: ") if password != password2: print("ERROR. Passwords did not match") sys.exit(0)