def test_decrypt_private_key(self): master_key = MasterKey(crypted_key=decodehexstr("be4afa6923ad06790b0f8c3345131499cf2b149ca422bd11a7e67a76347c51a456a2d626f75da1ff809632fca7165d71"), salt=decodehexstr("8cdcbd8a494b0eeb"), derivation_method=MasterKey.DERIVMETHOD_EVP_SHA512, derive_iterations=45193, other_derivation_parameters="") #Decrypt the master crypted_key using the passphrase plain_masterkey = decrypt_masterkey(master_key, "hello") print "plain_masterkey:", hexstr(plain_masterkey) assert hexstr(plain_masterkey) == "56722b42c4b9f8689fe9b38745fe75af92d0a50d6fd94b34de6b6d5e287bbed3" #Decrypt a crypted_secret public_key = decodehexstr("046a82d73af2cc093e3df7ae0185f045946970bcd5f0ef26f82d4f9a24e0d50f977c51e311e079e3183cfadd67d9b3f089fe7ba94a196c365fbd9e03b8c423787d") crypted_secret = decodehexstr("ff914ab69f58af92ac56de85051441e729cc51e11608d563e2a266ce3b8c59f573ed6a1828ff98fadb345890b6ed2626") crypter2 = Crypter() crypter2.set_key(plain_masterkey, doublesha256(public_key)) secret = crypter2.decrypt(crypted_secret) print "secret:", hexstr(secret) assert hexstr(secret) == "1c7552a9b755d29d081efd71f7811cc8ab2c9f2c634f489e6b45700711c8a304" #Test the secret k = KEY() k.set_secret(secret) assert k.get_pubkey() == public_key sig1 = k.sign("sign something") k2 = KEY() k2.set_pubkey(public_key) assert k2.verify("sign something", sig1) == 1
def hash_blockheader(blockheader): if blockheader.hash: return blockheader.hash if not blockheader.rawdata: blockheader.rawdata = BLOCK_SERIALIZE.serialize(blockheader) blockheader.hash = Uint256.from_bytestr(doublesha256(blockheader.rawdata)) return blockheader.hash
def mine_block(hash_prev, block_height, time_source, difficulty_bits, transactions, coinbase_txout_list, coinbase_flags=["/P2SH/"], nonce_changer=default_nonce_changer): template = BlockheaderTemplate(hash_prev, block_height, coinbase_txout_list, transactions, time_source.get_time(), difficulty_bits, coinbase_flags=coinbase_flags) difficulty_target = uint256_difficulty(difficulty_bits) hash_found = False while not hash_found: hash = Uint256.from_bytestr(doublesha256( template.get_serialized())) if (hash <= difficulty_target): hash_found = True else: nonce_changer(template) return (template.get_block(), template)
def sign_transaction_input(tx, input_index, txout_script, intput_script_type, secret, compressed_pubkey=True): # Set all txin to empty txin_scripts_save = [txin.script for txin in tx.in_list] for txin in tx.in_list: txin.script = Script([]) # Set the current input script to the outpoint's script value tx.in_list[input_index].script = txout_script # Serialize and append hash type enctx = TxSerializer().serialize(tx) + b"\x01\x00\x00\x00" # Get hash and Sign txhash = doublesha256(enctx) key = KEY() key.set_secret(secret, compressed_pubkey) signature = key.sign(txhash) + "\x01" # append hash_type SIGHASH_ALL # Restore Txin scripts for txin, script_save in zip(tx.in_list, txin_scripts_save): txin.script = script_save # Set the signed script if intput_script_type == TX_PUBKEYHASH: tx.in_list[input_index].script = make_script_pubkeyhash_sig( key.get_pubkey(), signature) if intput_script_type == TX_PUBKEY: tx.in_list[input_index].script = make_script_pubkey_sig(signature)
def hash_tx(tx): if tx.hash: return tx.hash if not tx.rawdata: tx.rawdata = TX_SERIALIZE.serialize(tx) tx.hash = Uint256.from_bytestr(doublesha256(tx.rawdata)) return tx.hash
def decode_base58check(data, preserve_leading_zeros=True): raw = preserve_leading_zeros and (count_leading_base58_zeros(data) * "\0") or "" raw += base256encode(base58decode(data)) if len(raw) < 4: raise Exception("base58check: format error") content, check = raw[:-4], raw[-4:] digest2 = doublesha256(content) if digest2[:4] != check: raise Exception("base58check: checksum error %s != %s" % (hexstr(digest2[:4]), hexstr(check))) return content
def decode_base58check(data, preserve_leading_zeros=True): raw = preserve_leading_zeros and (count_leading_base58_zeros(data) * "\0") or "" raw += base256encode(base58decode(data)) if len(raw) < 4: raise Exception("base58check: format error") content, check = raw[:-4], raw[-4:] digest2 = doublesha256(content) if (digest2[:4] != check): raise Exception("base58check: checksum error %s != %s" % (hexstr(digest2[:4]), hexstr(check))) return (content)
def get_private_key_secret(self, public_key): if public_key in self.wallet_database.keys: # private key is not crypted k = KEY() k.set_privkey(self.wallet_database.keys[public_key].private_key) return k.get_secret() crypted_secret = self.wallet_database.get_crypted_keys()[public_key] for key in self.plain_masterkeys: self.crypter.set_key(key, doublesha256(public_key)) secret = self.crypter.decrypt(crypted_secret) k = KEY() is_compressed = len(public_key) == 33 k.set_secret(secret, is_compressed) if k.get_pubkey() == public_key: return secret raise KeyDecryptException("Can't decrypt private key, wallet not unlocked or incorrect masterkey")
def encode_base58check(content, preserve_leading_zeros=True): """ Encode a bytestring (bid endian) as base58 with checksum. preserve_leading_zeros: argument used for MAIN bitcoin addresses (e.g.ADDRESSVERSION == 0) to preserve base256 leading zeros as base58 zeros ('1'). For example: addrversion=00,hash160=00602005b16851c4f9d0e2c82fa161ac8190e04c will give the bitcoin address: 112z9tWej11X94khKKzofFgWbdhiXLeHPD """ data = content + doublesha256(content)[:4] leading_zeros = None if preserve_leading_zeros: leading_zeros = 0 while data[leading_zeros] == "\x00": leading_zeros += 1 return base58encode(base256decode(data), leading_zeros=leading_zeros)
def encode_base58check(content, preserve_leading_zeros=True): """ Encode a bytestring (bid endian) as base58 with checksum. preserve_leading_zeros: argument used for MAIN bitcoin addresses (e.g.ADDRESSVERSION == 0) to preserve base256 leading zeros as base58 zeros ('1'). For example: addrversion=00,hash160=00602005b16851c4f9d0e2c82fa161ac8190e04c will give the bitcoin address: 112z9tWej11X94khKKzofFgWbdhiXLeHPD """ data = content + doublesha256(content)[:4] leading_zeros = None if preserve_leading_zeros: leading_zeros = 0 while data[leading_zeros] == "\x00": leading_zeros += 1 return (base58encode(base256decode(data), leading_zeros=leading_zeros))
def get_private_key_secret(self, public_key): if public_key in self.wallet_database.keys: # private key is not crypted k = KEY() k.set_privkey(self.wallet_database.keys[public_key].private_key) return k.get_secret() crypted_secret = self.wallet_database.get_crypted_keys()[public_key] for key in self.plain_masterkeys: self.crypter.set_key(key, doublesha256(public_key)) secret = self.crypter.decrypt(crypted_secret) k = KEY() is_compressed = len(public_key) == 33 k.set_secret(secret, is_compressed) if k.get_pubkey() == public_key: return secret raise KeyDecryptException( "Can't decrypt private key, wallet not unlocked or incorrect masterkey" )
def create(self, passphrase): self.wallet_database.begin_updates() crypter = Crypter() #first create masterkey master_key = new_masterkey(passphrase) plain_masterkey = decrypt_masterkey(master_key, passphrase) self.wallet_database.add_master_key(master_key) #create transaction pool for i in range(100): k = KEY() k.generate(True) public_key = k.get_pubkey() crypter.set_key(plain_masterkey, doublesha256(public_key)) crypted_secret = crypter.encrypt(k.get_secret()) self.wallet_database.add_crypted_key(public_key, crypted_secret) pool_key = WalletPoolKey(i, 60000, time.time(), public_key) self.wallet_database.add_poolkey(pool_key) self.wallet_database.commit_updates() self.load()
def create(self, passphrase): self.wallet_database.begin_updates() crypter = Crypter() #first create masterkey master_key = new_masterkey(passphrase) plain_masterkey = decrypt_masterkey(master_key, passphrase) self.wallet_database.add_master_key(master_key) #create transaction pool for i in range(100): k = KEY() k.generate(True) public_key = k.get_pubkey() crypter.set_key(plain_masterkey, doublesha256(public_key)) crypted_secret = crypter.encrypt(k.get_secret()) self.wallet_database.add_crypted_key(public_key, crypted_secret) pool_key = WalletPoolKey(i, 60000, time.time(), public_key) self.wallet_database.add_poolkey(pool_key) self.wallet_database.commit_updates() self.load()
def sign_transaction_input(tx, input_index, txout_script, intput_script_type, secret, compressed_pubkey=True): # Set all txin to empty txin_scripts_save = [txin.script for txin in tx.in_list] for txin in tx.in_list: txin.script = Script([]) # Set the current input script to the outpoint's script value tx.in_list[input_index].script = txout_script # Serialize and append hash type enctx = TxSerializer().serialize(tx) + b"\x01\x00\x00\x00" # Get hash and Sign txhash = doublesha256(enctx) key = KEY() key.set_secret(secret, compressed_pubkey) signature = key.sign(txhash) + "\x01" # append hash_type SIGHASH_ALL # Restore Txin scripts for txin, script_save in zip(tx.in_list, txin_scripts_save): txin.script = script_save # Set the signed script if intput_script_type == TX_PUBKEYHASH: tx.in_list[input_index].script = make_script_pubkeyhash_sig(key.get_pubkey(), signature) if intput_script_type == TX_PUBKEY: tx.in_list[input_index].script = make_script_pubkey_sig(signature)
def test_decrypt_private_key(self): master_key = MasterKey(crypted_key=decodehexstr( "be4afa6923ad06790b0f8c3345131499cf2b149ca422bd11a7e67a76347c51a456a2d626f75da1ff809632fca7165d71" ), salt=decodehexstr("8cdcbd8a494b0eeb"), derivation_method=MasterKey. DERIVMETHOD_EVP_SHA512, derive_iterations=45193, other_derivation_parameters="") #Decrypt the master crypted_key using the passphrase plain_masterkey = decrypt_masterkey(master_key, "hello") print "plain_masterkey:", hexstr(plain_masterkey) assert hexstr( plain_masterkey ) == "56722b42c4b9f8689fe9b38745fe75af92d0a50d6fd94b34de6b6d5e287bbed3" #Decrypt a crypted_secret public_key = decodehexstr( "046a82d73af2cc093e3df7ae0185f045946970bcd5f0ef26f82d4f9a24e0d50f977c51e311e079e3183cfadd67d9b3f089fe7ba94a196c365fbd9e03b8c423787d" ) crypted_secret = decodehexstr( "ff914ab69f58af92ac56de85051441e729cc51e11608d563e2a266ce3b8c59f573ed6a1828ff98fadb345890b6ed2626" ) crypter2 = Crypter() crypter2.set_key(plain_masterkey, doublesha256(public_key)) secret = crypter2.decrypt(crypted_secret) print "secret:", hexstr(secret) assert hexstr( secret ) == "1c7552a9b755d29d081efd71f7811cc8ab2c9f2c634f489e6b45700711c8a304" #Test the secret k = KEY() k.set_secret(secret) assert k.get_pubkey() == public_key sig1 = k.sign("sign something") k2 = KEY() k2.set_pubkey(public_key) assert k2.verify("sign something", sig1) == 1
def mine_block(hash_prev, block_height, time_source, difficulty_bits, transactions, coinbase_txout_list, coinbase_flags=["/P2SH/"], nonce_changer=default_nonce_changer): template = BlockheaderTemplate(hash_prev, block_height, coinbase_txout_list, transactions, time_source.get_time(), difficulty_bits, coinbase_flags=coinbase_flags) difficulty_target = uint256_difficulty(difficulty_bits) hash_found = False while not hash_found: hash = Uint256.from_bytestr(doublesha256(template.get_serialized())) if (hash <= difficulty_target): hash_found = True else: nonce_changer(template) return (template.get_block(), template)
def op_hash256(vm, instr): if (len(vm.stack) < 1): raise Exception("OP_HASH256: Missing argument") x = vm.stack.pop() vm.stack.append(doublesha256(x))
), salt=decodehexstr("8cdcbd8a494b0eeb"), derivation_method=MasterKey.DERIVMETHOD_EVP_SHA512, derive_iterations=45193, other_derivation_parameters="") #Decrypt the master crypted_key using the passphrase plain_masterkey = decrypt_masterkey(master_key, "hello") #Decrypt a crypted_secret public_key = decodehexstr( "046a82d73af2cc093e3df7ae0185f045946970bcd5f0ef26f82d4f9a24e0d50f977c51e311e079e3183cfadd67d9b3f089fe7ba94a196c365fbd9e03b8c423787d" ) crypted_secret = decodehexstr( "ff914ab69f58af92ac56de85051441e729cc51e11608d563e2a266ce3b8c59f573ed6a1828ff98fadb345890b6ed2626" ) crypter2 = Crypter() crypter2.set_key(plain_masterkey, doublesha256(public_key)) secret = crypter2.decrypt(crypted_secret) print hexstr(secret) #Test the secret k = KEY() k.set_secret(secret) sig = signature1 = k.sign("sign something") k2 = KEY() k2.set_pubkey(public_key) print k2.verify("sign something", sig) #Create a new masterkey m = new_masterkey("hello hello") print m print hexstr(decrypt_masterkey(m, "hello hello"))
def op_hash256(vm, instr): if (len(vm.stack) < 1): raise Exception("OP_HASH256: Missing argument") x = vm.stack.pop() vm.stack.append(doublesha256(x))
def checksig(vm, sig_param, pubkey_param): transaction, inputindex, unspent_script = vm.checksig_data #Hash type is the last byte of the signature hash_type, sig = ord(sig_param[-1]), sig_param[:-1] # last 5 bits of hash_type : 1=SIGHASH_ALL,2=SIGHASH_NONE, 3=SIGHASH_SINGLE # SIGHASH_ANYONECANPAY = 0x80 # For performance reasons no full copy is made of the transaction # although it would be simpler to read. # e.g. tx_tmp = copy.deepcopy(transaction) # The input scripts are saved and then restored. tx_tmp = Tx(transaction.version, [ TxIn(txin.previous_output, txin.script, txin.sequence) for txin in transaction.in_list ], [TxOut(txout.value, txout.script) for txout in transaction.out_list], transaction.locktime) #Save input scripts to restore them later #inlist = transaction.in_list #outlist = transaction.out_list #inscripts = [txin.script for txin in transaction.in_list] #TODO: blank out ouputs depending of hash_type (SIGHASH_NONE, SIGHASH_SINGLE) if (hash_type & SIGHASH_MASK == SIGHASH_NONE): tx_tmp.out_list = [] if (hash_type & SIGHASH_MASK == SIGHASH_SINGLE): if (inputindex > len(tx_tmp.out_list)): raise Exception( "OP_CHECKSIG: no corresponding output for input %d using SIGHASH_SINGLE " % (inputindex)) #n-1 empty TxOuts + original Txout tx_tmp.out_list = [TxOut(-1, Script([])) for _ in range(inputindex)] + \ [tx_tmp.out_list[inputindex]] if (hash_type & SIGHASH_MASK == SIGHASH_SINGLE or hash_type & SIGHASH_MASK == SIGHASH_NONE): # let others update at will for i in range(len(tx_tmp.in_list)): if i != inputindex: tx_tmp.in_list[i].sequence = 0 #blank out other inputs in case of SIGHASH_ANYONECANPAY if (hash_type & SIGHASH_ANYONECANPAY): tx_tmp.in_list = [tx_tmp.in_list[inputindex]] inputindex = 0 #blank out input scripts for txin in tx_tmp.in_list: txin.script = Script([]) #except the current one that is replaced by the signed part (e.g. from the last OP_CODESEPARATOR) # of current_script with signature push_data removed # note: only 'optimal' push_data instructions with the same signature are removed current_script = Script( filter(lambda instr: instr != push_data_instruction(sig_param), vm.current_script.signed_part().instructions)) tx_tmp.in_list[inputindex].script = current_script #serialize and append hash type enctx = TxSerializer().serialize(tx_tmp) + chr(hash_type) + b"\x00\x00\x00" #print "enctx:", hexstr(enctx) #print "sig:", hexstr(sig) #print "pubkey:", hexstr(pubkey_param) #Get hash hash = doublesha256(enctx) #Verify key = KEY() key.set_pubkey(pubkey_param) #ECDSA_verify: 1 = OK, 0=NOK, -1=ERROR result = key.verify(hash, sig) == 1 if not result: pass #Restore transaction scripts #for txin, script in zip(inlist,inscripts): # txin.script = script #transaction.in_list = inlist return (result)
from coinpy.tools.hex import hexstr from coinpy.model.wallet.masterkey import MasterKey from coinpy.tools.bitcoin.sha256 import doublesha256 from coinpy.tools.crypto.ecdsa.ecdsa_ssl import KEY master_key = MasterKey(crypted_key=decodehexstr("be4afa6923ad06790b0f8c3345131499cf2b149ca422bd11a7e67a76347c51a456a2d626f75da1ff809632fca7165d71"), salt=decodehexstr("8cdcbd8a494b0eeb"), derivation_method=MasterKey.DERIVMETHOD_EVP_SHA512, derive_iterations=45193, other_derivation_parameters="") #Decrypt the master crypted_key using the passphrase plain_masterkey = decrypt_masterkey(master_key, "hello") #Decrypt a crypted_secret public_key = decodehexstr("046a82d73af2cc093e3df7ae0185f045946970bcd5f0ef26f82d4f9a24e0d50f977c51e311e079e3183cfadd67d9b3f089fe7ba94a196c365fbd9e03b8c423787d") crypted_secret = decodehexstr("ff914ab69f58af92ac56de85051441e729cc51e11608d563e2a266ce3b8c59f573ed6a1828ff98fadb345890b6ed2626") crypter2 = Crypter() crypter2.set_key(plain_masterkey, doublesha256(public_key)) secret = crypter2.decrypt(crypted_secret) print hexstr(secret) #Test the secret k = KEY() k.set_secret(secret) sig = signature1 = k.sign("sign something") k2 = KEY() k2.set_pubkey(public_key) print k2.verify("sign something", sig) #Create a new masterkey m = new_masterkey("hello hello") print m print hexstr(decrypt_masterkey(m, "hello hello" ))
def checksig(vm, sig_param, pubkey_param): transaction, inputindex, unspent_script = vm.checksig_data #Hash type is the last byte of the signature hash_type, sig = ord(sig_param[-1]), sig_param[:-1] # last 5 bits of hash_type : 1=SIGHASH_ALL,2=SIGHASH_NONE, 3=SIGHASH_SINGLE # SIGHASH_ANYONECANPAY = 0x80 # For performance reasons no full copy is made of the transaction # although it would be simpler to read. # e.g. tx_tmp = copy.deepcopy(transaction) # The input scripts are saved and then restored. tx_tmp = Tx(transaction.version, [TxIn(txin.previous_output, txin.script, txin.sequence) for txin in transaction.in_list], [TxOut(txout.value, txout.script) for txout in transaction.out_list], transaction.locktime) #Save input scripts to restore them later #inlist = transaction.in_list #outlist = transaction.out_list #inscripts = [txin.script for txin in transaction.in_list] #TODO: blank out ouputs depending of hash_type (SIGHASH_NONE, SIGHASH_SINGLE) if (hash_type & SIGHASH_MASK == SIGHASH_NONE): tx_tmp.out_list = [] if (hash_type & SIGHASH_MASK == SIGHASH_SINGLE): if (inputindex > len(tx_tmp.out_list)): raise Exception("OP_CHECKSIG: no corresponding output for input %d using SIGHASH_SINGLE " % (inputindex)) #n-1 empty TxOuts + original Txout tx_tmp.out_list = [TxOut(-1, Script([])) for _ in range(inputindex)] + \ [tx_tmp.out_list[inputindex]] if (hash_type & SIGHASH_MASK == SIGHASH_SINGLE or hash_type & SIGHASH_MASK == SIGHASH_NONE): # let others update at will for i in range(len(tx_tmp.in_list)): if i != inputindex: tx_tmp.in_list[i].sequence = 0 #blank out other inputs in case of SIGHASH_ANYONECANPAY if (hash_type & SIGHASH_ANYONECANPAY): tx_tmp.in_list = [tx_tmp.in_list[inputindex]] inputindex = 0 #blank out input scripts for txin in tx_tmp.in_list: txin.script = Script([]) #except the current one that is replaced by the signed part (e.g. from the last OP_CODESEPARATOR) # of current_script with signature push_data removed # note: only 'optimal' push_data instructions with the same signature are removed current_script = Script(filter(lambda instr: instr!=push_data_instruction(sig_param), vm.current_script.signed_part().instructions)) tx_tmp.in_list[inputindex].script = current_script #serialize and append hash type enctx = TxSerializer().serialize(tx_tmp) + chr(hash_type) + b"\x00\x00\x00" #print "enctx:", hexstr(enctx) #print "sig:", hexstr(sig) #print "pubkey:", hexstr(pubkey_param) #Get hash hash = doublesha256(enctx) #Verify key = KEY() key.set_pubkey(pubkey_param) #ECDSA_verify: 1 = OK, 0=NOK, -1=ERROR result = key.verify(hash, sig) == 1 if not result: pass #Restore transaction scripts #for txin, script in zip(inlist,inscripts): # txin.script = script #transaction.in_list = inlist return (result)