Пример #1
0
def encode_signature(tx_v, tx_r, tx_s) -> bytes:
    """
    Calculates byte representation of ECC signature from parameters
    :param tx_v:
    :param tx_r:
    :param tx_s:
    :return: bytes of ECC signature
    """
    if not isinstance(tx_v, int):
        raise ValueError("v is expected to be int")

    if tx_v > eth_common_constants.EIP155_CHAIN_ID_OFFSET:
        if tx_v % 2 == 0:
            tx_v = 28
        else:
            tx_v = 27

    if tx_v not in (27, 28):
        raise ValueError("v is expected to be int or long in range (27, 28)")

    # pyre-fixme[16]: Module `bitcoin` has no attribute `encode`.
    # pyre-fixme[16]: Module `bitcoin` has no attribute `encode`.
    v_bytes, r_bytes, s_bytes = rlp_utils.ascii_chr(tx_v - 27), bitcoin.encode(
        tx_r, 256), bitcoin.encode(tx_s, 256)
    return _left_0_pad_32(r_bytes) + _left_0_pad_32(s_bytes) + v_bytes
Пример #2
0
 def hash(self, branch, market, outcome, amount, difficulty, steps=1000):
     """
         It is formally defined as PoW: PoW(H, n) = BE(SHA3(SHA3(RLP(Hn)) o n))
         where:
         RLP(Hn) is the concatenation of buy shares data
         SHA3 is the SHA3 hash function accepting an arbitrary length series of
             bytes and evaluating to a series of 32 bytes (i.e. 256-bit);
         n is the nonce, a series of 32 bytes;
         o is the series concatenation operator;
         BE(X) evaluates to the value equal to X when interpreted as a
             big-endian-encoded integer.
         """
     #difficulty = branch.difficulty
     nonce_bin_prefix = '\x00' * (32 - len(struct.pack('>q', 0)))
     target = 2**254 / difficulty
     rlp_Hn = encode(branch, 256, 32) + encode(market, 256, 32) + encode(
         outcome, 256, 32) + encode(amount, 256, 32)
     for nonce in range(self.nonce, self.nonce + steps):
         nonce_bin = nonce_bin_prefix + struct.pack('>q', nonce)
         # BE(SHA3(SHA3(RLP(Hn)) o n))
         h = self.sha3((self.sha3(rlp_Hn) + nonce_bin))
         #log.debug('nonce found', nonce=nonce, hash=(h.encode('hex') or '0'))
         l256 = self.big_endian_to_int(h)
         if l256 < target:
             return decode(nonce_bin, 256)
     self.nonce = nonce
     return False
Пример #3
0
 def base_encoder_tests(self):
     self.assertEqual(b.encode(1029, 256), '\x04\x05')
     self.assertEqual(b.decode('DEADBEEF', 16), 3735928559)
     r = random.randrange(2**256)
     self.assertEqual(b.decode(b.changebase(b.encode(r, 16), 16, 58), 58),
                      r)
     self.assertEqual(b.base58export(b.base58check(r, 101, 34)), r)
Пример #4
0
def test_saveload2():
    s = tester.state()
    c = s.contract(saveload_code2)
    s.send(tester.k0, c, 0)
    assert bitcoin.encode(s.block.get_storage_data(c, 0),
                          256) == b'01ab' + b'\x00' * 28
    assert bitcoin.encode(s.block.get_storage_data(c, 1),
                          256) == b'01ab' + b'\x00' * 28
Пример #5
0
def test_saveload2():
    c = tester.Chain()
    x = c.contract(saveload_code2, language='serpent')
    c.tx(tester.k0, x.address, 0)
    assert bitcoin.encode(c.head_state.get_storage_data(x.address, 0),
                          256) == b'01ab' + b'\x00' * 28
    assert bitcoin.encode(c.head_state.get_storage_data(x.address, 1),
                          256) == b'01ab' + b'\x00' * 28
Пример #6
0
def test_p2p_broadcast(setup_tx_notify):
    #listen up kids, dont do this to generate private
    #keys that hold real money, or else you'll be robbed
    src_privkey = random.getrandbits(256)
    src_privkey = btc.encode(src_privkey, 16, 64) + '01'
    src_addr = btc.privtoaddr(src_privkey, magicbyte=get_p2pk_vbyte())
    dst_addr = btc.pubtoaddr('03' + btc.encode(random.getrandbits(256), 16),
                             get_p2pk_vbyte())

    jm_single().bc_interface.rpc('importaddress', [src_addr, "", False])
    jm_single().bc_interface.rpc('importaddress', [dst_addr, "", False])
    jm_single().bc_interface.rpc('generatetoaddress', [1, src_addr])
    jm_single().bc_interface.rpc('generate', [101])
    src_utxos = jm_single().bc_interface.rpc('listunspent',
                                             [0, 500, [src_addr]])

    inputs = [{
        'output': src_utxos[0]['txid'] + ':' + str(src_utxos[0]['vout'])
    }]
    miner_fee = 10000
    outs = [{
        'address': dst_addr,
        'value': int(src_utxos[0]['amount'] * 1e8) - miner_fee
    }]
    tx = btc.mktx(inputs, outs)
    tx = btc.sign(tx, 0, src_privkey)

    bad_tx = random.getrandbits(len(tx) * 4)
    bad_tx = btc.encode(bad_tx, 16, len(tx))

    utxo_before = jm_single().bc_interface.rpc('listunspent',
                                               [0, 500, [dst_addr]])

    #jm_single().bc_interface.rpc('sendrawtransaction', [tx])
    pushed = tor_broadcast_tx(tx,
                              None,
                              'regtest',
                              remote_hostport=('localhost', 18444))
    assert pushed

    pushed = tor_broadcast_tx(tx,
                              None,
                              'regtest',
                              remote_hostport=('localhost', 18444))
    assert not pushed  #node should already have the same tx, reject

    pushed = tor_broadcast_tx(bad_tx,
                              None,
                              'regtest',
                              remote_hostport=('localhost', 18444))
    assert not pushed  #bad tx should be rejected

    jm_single().bc_interface.rpc('generate', [1])
    utxo_after = jm_single().bc_interface.rpc('listunspent',
                                              [0, 500, [dst_addr]])

    return len(utxo_after) - 1 == len(utxo_before)
Пример #7
0
def der_encode_sig(v, r, s):
    b1, b2 = safe_hexlify(encode(r, 256)), safe_hexlify(encode(s, 256))
    if len(b1) and b1[0] in '89abcdef':
        b1 = '00' + b1
    if len(b2) and b2[0] in '89abcdef':
        b2 = '00' + b2
    left = '02' + encode(len(b1) // 2, 16, 2) + b1
    right = '02' + encode(len(b2) // 2, 16, 2) + b2
    return '30' + encode(len(left + right) // 2, 16, 2) + left + right
Пример #8
0
def serialize_header(inp):
    o = encode(inp['version'], 256, 4)[::-1] + \
        binascii.unhexlify(inp['prev_block_hash'])[::-1] + \
        binascii.unhexlify(inp['merkle_root'])[::-1] + \
        encode(inp['timestamp'], 256, 4)[::-1] + \
        encode(inp['bits'], 256, 4)[::-1] + \
        encode(inp['nonce'], 256, 4)[::-1]
    h = binascii.hexlify(bin_sha256(bin_sha256(o))[::-1]).decode()
    if inp.get('hash'):
        assert h == inp['hash'], (hashlib.sha256(o), inp['hash'])
    return binascii.hexlify(o).decode()
Пример #9
0
def sha3(*args):
    data = ''
    for i in args:
        if isinstance(i, (int, long)):
            data += encode(i, 256, 32)
        if isinstance(i, (list, tuple)):
            data += ''.join(encode(j, 256, 32) for j in i)
        if isinstance(i, str):
            data += i
    result = decode(_sha3(data).digest(), 256)
    if result > 2**255:
        result  -= 2**256
    return result
Пример #10
0
def sha3(*args):
    data = ""
    for i in args:
        if isinstance(i, (int, long)):
            data += encode(i, 256, 32)
        if isinstance(i, (list, tuple)):
            data += "".join(encode(j, 256, 32) for j in i)
        if isinstance(i, str):
            data += i
    result = decode(_sha3(data).digest(), 256)
    if result > 2 ** 255:
        result -= 2 ** 256
    return result
Пример #11
0
    def check__pow(self, branch, market, outcome, amount, nonce):
        assert len(nonce) == 32
        #difficulty = branch.difficulty
        difficulty = 10000
        metadata = encode(branch, 256, 32) + encode(market, 256, 32) + encode(
            outcome, 256, 32) + encode(amount, 256, 32)
        h = self.sha3(self.sha3(metadata) + nonce)
        return self.big_endian_to_int(h) < 2**254 / difficulty


#base 256, 32 bytes each (<= 256)
#encode(val, base, minlen=0)
#decode(string, base)
Пример #12
0
def sign_donation_tx(tx, i, priv):
    from bitcoin.main import fast_multiply, decode_privkey, G, inv, N
    from bitcoin.transaction import der_encode_sig
    k = sign_k
    hashcode = btc.SIGHASH_ALL
    i = int(i)
    if len(priv) <= 33:
        priv = btc.safe_hexlify(priv)
    pub = btc.privkey_to_pubkey(priv)
    address = btc.pubkey_to_address(pub)
    signing_tx = btc.signature_form(tx, i, btc.mk_pubkey_script(address),
                                    hashcode)

    msghash = btc.bin_txhash(signing_tx, hashcode)
    z = btc.hash_to_int(msghash)
    # k = deterministic_generate_k(msghash, priv)
    r, y = fast_multiply(G, k)
    s = inv(k, N) * (z + r * decode_privkey(priv)) % N
    rawsig = 27 + (y % 2), r, s

    sig = der_encode_sig(*rawsig) + btc.encode(hashcode, 16, 2)
    # sig = ecdsa_tx_sign(signing_tx, priv, hashcode)
    txobj = btc.deserialize(tx)
    txobj["ins"][i]["script"] = btc.serialize_script([sig, pub])
    return btc.serialize(txobj)
Пример #13
0
def segwit_sign(tx,
                i,
                priv,
                amount,
                hashcode=SIGHASH_ALL,
                script=None,
                separator_index=None):
    i = int(i)
    txobj = tx if isinstance(tx, dict) else deserialize(tx)
    if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes))
                                     or not re.match('^[0-9a-fA-F]*$', tx)):
        return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv))
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    pub = privkey_to_pubkey(priv)
    address = pubkey_to_address(pub)
    wscript = mk_pubkey_script(address) if not script else script
    stripped_script = segwit_strip_script_separator(wscript, separator_index)
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       stripped_script,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script]
    return serialize(txobj)
Пример #14
0
 def generateHexCompressedPublicKey(self, public_key):
     (public_key_x, public_key_y) = public_key
     if public_key_y % 2 == 0:
       compressed_prefix = '02'
     else:
       compressed_prefix = '03'
     return compressed_prefix + bitcoin.encode(public_key_x, 16)
Пример #15
0
def sign_donation_tx(tx, i, priv):
    from bitcoin.main import fast_multiply, decode_privkey, G, inv, N
    from bitcoin.transaction import der_encode_sig
    k = sign_k
    hashcode = btc.SIGHASH_ALL
    i = int(i)
    if len(priv) <= 33:
        priv = btc.safe_hexlify(priv)
    pub = btc.privkey_to_pubkey(priv)
    address = btc.pubkey_to_address(pub)
    signing_tx = btc.signature_form(
            tx, i, btc.mk_pubkey_script(address), hashcode)

    msghash = btc.bin_txhash(signing_tx, hashcode)
    z = btc.hash_to_int(msghash)
    # k = deterministic_generate_k(msghash, priv)
    r, y = fast_multiply(G, k)
    s = inv(k, N) * (z + r * decode_privkey(priv)) % N
    rawsig = 27 + (y % 2), r, s

    sig = der_encode_sig(*rawsig) + btc.encode(hashcode, 16, 2)
    # sig = ecdsa_tx_sign(signing_tx, priv, hashcode)
    txobj = btc.deserialize(tx)
    txobj["ins"][i]["script"] = btc.serialize_script([sig, pub])
    return btc.serialize(txobj)
Пример #16
0
def segwit_multisign(tx, i, script, pk, amount, hashcode=SIGHASH_ALL, separator_index=None):
    wscript = segwit_strip_script_separator(script, index=separator_index)
    signing_tx = segwit_signature_form(tx, i, wscript, amount, hashcode=hashcode)
    rawsig = ecdsa_raw_sign(hashlib.sha256(hashlib.sha256(
        binascii.unhexlify(signing_tx)).digest()).hexdigest(), pk)
    sig = der_encode_sig(*rawsig)+encode(hashcode, 16, 2)
    return sig
Пример #17
0
def tx_make_input_signature(tx, idx, script, privkey_str, hashcode):
    """
    Sign a single input of a transaction, given the serialized tx,
    the input index, the output's scriptPubkey, and the hashcode.

    privkey_str must be a hex-encoded private key

    TODO: move to virtualchain

    Return the hex signature.
    """
    pk = virtualchain.BitcoinPrivateKey(str(privkey_str))
    pubk = pk.public_key()

    priv = pk.to_hex()
    pub = pubk.to_hex()
    addr = pubk.address()

    signing_tx = bitcoin.signature_form(tx, idx, script, hashcode)
    txhash = bitcoin.bin_txhash(signing_tx, hashcode)

    # sign using uncompressed private key
    pk_uncompressed_hex, pubk_uncompressed_hex = get_uncompressed_private_and_public_keys(
        priv)
    sigb64 = sign_digest(txhash.encode('hex'), priv)

    # sanity check
    assert verify_digest(txhash.encode('hex'), pubk_uncompressed_hex, sigb64)

    sig_r, sig_s = decode_signature(sigb64)
    sig_bin = ecdsa.util.sigencode_der(sig_r, sig_s, ecdsa.SECP256k1.order)
    sig = sig_bin.encode('hex') + bitcoin.encode(hashcode, 16, 2)
    return sig
Пример #18
0
 def genCompressedPublicKey_(self, public_key):
     (x, y) = public_key
     if (y % 2) == 0:
         compressed_prefix = '02'
     else:
         compressed_prefix = '03'
     hex_compressed_public_key = compressed_prefix + bitcoin.encode(x, 16)
     return hex_compressed_public_key
Пример #19
0
def createPriKey(wifKey):
    wif_encoding_private_key = wifKey
    wifUNCompressed = bitcoin.decode_privkey(wif_encoding_private_key,
                                             'wif_compressed')
    decimalToHex = bitcoin.encode(wifUNCompressed, 16)  # return str
    cv = Curve.get_curve('secp256k1')
    pv_key = ECPrivateKey(int("0x" + decimalToHex, 16), cv)  # 16进制str 转为 int
    return pv_key
Пример #20
0
 def pk_function_tests(self):
   seed = 'horse rabbit cow'
   k58 = b.makepk(seed,58)
   k16 = b.makepk(seed,16)
   self.assertEqual(k58,'5KLipFbYY8NTU4SJdKmzidVsw3WhdrwsmCTbLgYVCY4NWF3Hwxs')
   self.assertEqual(k16,'c8cd79f6a89a089ecf0035b1cce059cbbecd85d2d6a2a5edb023a825a3cb2624')
   self.assertEqual(b.base58export('18Tw87wAwjWXg3RQ2oY4oTsn68scDQ2gsL'),467443130064359750498234077082078405762457967729)
   self.assertEqual(b.encode(b.base58export(k58),16),k16)
Пример #21
0
def generate_key():
    #generate a random private key
    valid_private_key = False
    while not valid_private_key:
        private_key = bitcoin.random_key()
        decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
        valid_private_key = 0 < decoded_private_key < bitcoin.N
    #print ('Private Key (hex) is: ' + private_key)
    #print ('private Key (decimal) is: ' + str(decoded_private_key))

    #convert private key to WIF format
    wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key,
                                                     'wif')
    #print('Private Key (WIF) is: ' + wif_encoded_private_key)

    # Add sufix '01' to indicate a compressed private Key
    compressed_private_key = private_key + '01'
    #print ('Private Key Compressed (hex) is: ' + compressed_private_key)

    # generate a WIF format from the compressed private key (WIF-compressed)
    wif_compressed_private_key = bitcoin.encode_privkey(
        bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
    #print ('Private Key (WIF-compressed) is: ' + wif_compressed_private_key)

    # Multiply de EC generator G with the priveate key to get a public key point
    public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
    #print ('Public Key (x,y) coordinates are: ' + str(public_key))

    # Encode as hex, prefix 04
    hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex')
    #print ('Public Key (hex) is: ' + hex_encoded_public_key)

    # Compress public key, adjust prefix depending on whether y is even or odd
    (public_key_x, public_key_y) = public_key
    if public_key_y % 2 == 0:
        compressed_prefix = '02'
    else:
        compressed_prefix = '03'
    hex_compressed_public_key = compressed_prefix + bitcoin.encode(
        public_key_x, 16)
    #print ('Compressed Public Key is: ' + hex_compressed_public_key)

    # Generate bitcoin address from public Key
    #print ('Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(public_key))

    # Generate compressedd bitcoin address from compressed public key
    #print ('Compressed Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(hex_compressed_public_key))

    compressed_address_base58check = bitcoin.pubkey_to_address(
        hex_compressed_public_key)

    kson = {
        "wif1": wif_encoded_private_key,
        "wif": wif_compressed_private_key,
        "key": compressed_address_base58check
    }

    return kson
Пример #22
0
def create_bitcoin_public_key(private_key):
  decoded_private_key = bitcoin.decode_privkey(private_key, "hex")
  public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
  (public_key_x, public_key_y) = public_key
  compressed_prefix = "02" if (public_key_y % 2) == 0 else "03"
  # 64 represents the minimum length of the string required returned back.
  # Zeros will be prepended to a string until it meets the length requirement.
  # Less characters than 64 will result in an invalid public key.
  return compressed_prefix + bitcoin.encode(public_key_x, 16, 64)
Пример #23
0
def change_base(instr, bef, aft, minlen=0):
    if bef == aft:
        try:
            return code_strings[bef][0] * (
                minlen - len(instr)) + instr if minlen > len(instr) else instr
        except Exception as e:
            raise e
    else:
        return encode(decode(instr, bef), aft, minlen)
Пример #24
0
    def __init__(self, state, code, sender, gas, endowment, language):
        if language not in _t.languages:
            _t.languages[language] = __import__(language)
        language = _t.languages[language]
        
        if os.path.exists(code):
            cache = code.replace('.se', '.sec')
            if os.path.exists(cache):
                cache_made = os.path.getmtime(cache)
                code_made = os.path.getmtime(code)
                if code_made > cache_made:
                    with open(cache, 'wb') as f:
                        print Fore.YELLOW + Style.BRIGHT + 'Stale cache, recompiling...' + Style.RESET_ALL
                        with timer():
                            evm = language.compile(code)
                            sig = language.mk_full_signature(code)
                            evm_len = encode(len(evm), 256, 2)
                            sig_len = encode(len(sig), 256, 2)
                            f.write(evm_len + evm + sig_len + sig)
                else:
                    print Fore.YELLOW + Style.BRIGHT + 'Loading from cache...' + Style.RESET_ALL
                    with open(cache, 'rb') as f:
                        with timer():
                            evm_len = decode(f.read(2), 256)
                            evm = f.read(evm_len)
                            sig_len = decode(f.read(2), 256)
                            sig = f.read(sig_len)
            else:
                with open(cache, 'wb') as f:
                    print Fore.YELLOW + Style.BRIGHT + 'Generating cache...' + Style.RESET_ALL
                    with timer():
                        evm = language.compile(code)
                        sig = language.mk_full_signature(code)
                        evm_len = encode(len(evm), 256, 2)
                        sig_len = encode(len(sig), 256, 2)
                        f.write(evm_len + evm + sig_len + sig)

            with suppressed_output():
                self.address = _t.encode_hex(state.evm(evm, sender, endowment, gas))
            self._translator = _t.abi.ContractTranslator(sig)
            assert len(state.block.get_code(self.address)), "Contract code empty"
            for funcname in self._translator.function_data:
                vars(self)[funcname] = make_dispatcher(state, self, funcname)
Пример #25
0
 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
Пример #26
0
 def pk_function_tests(self):
     seed = 'horse rabbit cow'
     k58 = b.makepk(seed, 58)
     k16 = b.makepk(seed, 16)
     self.assertEqual(
         k58, '5KLipFbYY8NTU4SJdKmzidVsw3WhdrwsmCTbLgYVCY4NWF3Hwxs')
     self.assertEqual(
         k16,
         'c8cd79f6a89a089ecf0035b1cce059cbbecd85d2d6a2a5edb023a825a3cb2624')
     self.assertEqual(b.base58export('18Tw87wAwjWXg3RQ2oY4oTsn68scDQ2gsL'),
                      467443130064359750498234077082078405762457967729)
     self.assertEqual(b.encode(b.base58export(k58), 16), k16)
Пример #27
0
def trade_pow(branch, market, address, trade_nonce, difficulty=10000):
    nonce = 0
    target = 2 ** 254 / difficulty
    address = decode(address, 16)
    data = [branch, market, address, trade_nonce]
    encoder = lambda x: encode(x, 256, 32)
    decoder = lambda x: decode(x, 256)
    first_hash = sha3("".join(map(encoder, data))).digest()
    while True:
        h = decoder(sha3(first_hash + encoder(nonce)).digest())
        if h < target:
            return nonce
        nonce += 1
Пример #28
0
def trade_pow(branch, market, address, trade_nonce, difficulty=10000):
    nonce = 0
    target = 2**254/difficulty
    address = decode(address, 16)
    data = [branch, market, address, trade_nonce]
    encoder = lambda x: encode(x, 256, 32)
    decoder = lambda x: decode(x, 256)
    first_hash = sha3(''.join(map(encoder, data))).digest()
    while True:
        h = decoder(sha3(first_hash+encoder(nonce)).digest())
        if h < target:
            return nonce
        nonce += 1
Пример #29
0
def bech32_multisign(tx, i, priv, amount, script, hashcode=SIGHASH_ALL):
    from bitcoin import segwit_signature_form, ecdsa_raw_sign, der_encode_sig
    i = int(i)
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       script,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    return sig
Пример #30
0
def segwit_sign(tx, i, priv, amount, hashcode=SIGHASH_ALL, script=None, separator_index=None):
    i = int(i)
    txobj = tx if isinstance(tx, dict) else deserialize(tx)
    if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx)):
        return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv))
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    pub = privkey_to_pubkey(priv)
    address = pubkey_to_address(pub)
    wscript = mk_pubkey_script(address) if not script else script
    stripped_script = segwit_strip_script_separator(wscript, separator_index)
    signing_tx = segwit_signature_form(tx, i, stripped_script, amount, hashcode=hashcode)
    rawsig = ecdsa_raw_sign(hashlib.sha256(hashlib.sha256(binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig)+encode(hashcode, 16, 2)
    txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script]
    return serialize(txobj)
Пример #31
0
def tx_make_input_signature(tx, idx, script, privkey_str, hashcode):
    """
    Sign a single input of a transaction, given the serialized tx,
    the input index, the output's scriptPubkey, and the hashcode.

    TODO: move to virtualchain

    Return the hex signature.
    """

    pk = virtualchain.BitcoinPrivateKey(str(privkey_str))
    pubk = pk.public_key()

    priv = pk.to_hex()
    pub = pubk.to_hex()
    addr = pubk.address()

    signing_tx = bitcoin.signature_form(tx, idx, script, hashcode)
    txhash = bitcoin.bin_txhash(signing_tx, hashcode)

    # sign using uncompressed private key
    pk_uncompressed_hex, pubk_uncompressed_hex = get_uncompressed_private_and_public_keys(
        priv)

    sk = ecdsa.SigningKey.from_string(pk_uncompressed_hex.decode('hex'),
                                      curve=ecdsa.SECP256k1)
    sig_bin = sk.sign_digest(txhash, sigencode=ecdsa.util.sigencode_der)

    # enforce low-s
    sig_r, sig_s = ecdsa.util.sigdecode_der(sig_bin, ecdsa.SECP256k1.order)
    if sig_s * 2 >= ecdsa.SECP256k1.order:
        log.debug("High-S to low-S")
        sig_s = ecdsa.SECP256k1.order - sig_s

    sig_bin = ecdsa.util.sigencode_der(sig_r, sig_s, ecdsa.SECP256k1.order)

    # sanity check
    vk = ecdsa.VerifyingKey.from_string(
        pubk_uncompressed_hex[2:].decode('hex'), curve=ecdsa.SECP256k1)
    assert vk.verify_digest(sig_bin,
                            txhash,
                            sigdecode=ecdsa.util.sigdecode_der
                            ), "Failed to verify signature ({}, {})".format(
                                sig_r, sig_s)

    sig = sig_bin.encode('hex') + bitcoin.encode(hashcode, 16, 2)
    return sig
Пример #32
0
def sarah(hexli):
    private_key = hexli
    decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
    wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
    compressed_private_key = private_key + '01'
    wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(private_key, 'hex'), 'wif_compressed')
    public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
    hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex')
    (public_key_x, public_key_y) = public_key
    if public_key_y % 2 == 0:
      compressed_prefix = '02'
    else:
      compressed_prefix = '03'
    hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
    non_compressed_adress = bitcoin.pubkey_to_address(public_key)
    compressed_address = bitcoin.pubkey_to_address(hex_compressed_public_key.encode("utf8"))
    return non_compressed_adress, compressed_address, wif_encoded_private_key, wif_compressed_private_key, private_key
Пример #33
0
def function_keys():

    valid_private_key = False  #randomize private key

    while not valid_private_key:
        private_key = bitcoin.random_key()
        decode_private_key = bitcoin.decode_privkey(private_key, 'hex')
        valid_private_key = 0 < decode_private_key < bitcoin.N

    print "Private Key (hex) is:", private_key
    print "Private Key (decimal) is:", decode_private_key
    wif_encode_private_key = bitcoin.encode_privkey(decode_private_key, 'wif')
    print "Private key (WIF) is:", wif_encode_private_key  # convert private key to wif format

    compressed_private_key = private_key + '01'
    print "Private key Compressed (hex) is:", compressed_private_key  # add '01' to indicate compressed private key

    wif_compressed_private_key = bitcoin.encode_privkey(
        bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
    print "Private Key (Wif-compressed) is:", wif_compressed_private_key

    public_key = bitcoin.fast_multiply(
        bitcoin.G, decode_private_key
    )  # multiply EC generator with the private key to have public key point
    print "Public Key (x, y) coordinates is:", public_key

    hex_encoded_public_key = bitcoin.encode_pubkey(
        public_key, 'hex')  # encoded public key with '04'
    print "Public Key (hex) is:", hex_encoded_public_key

    (public_key_x, public_key_y) = public_key  # compressed public key
    if (public_key_y % 2) == 0:
        compressed_prefix = '02'
    else:
        compressed_prefix = '03'
        hex_compressed_public_key = compressed_prefix + bitcoin.encode(
            public_key_x, 16)
    print "Compressed Public Key (hex) is:", hex_compressed_public_key
    print "Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(
        public_key)

    print "Compressed Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(
        hex_compressed_public_key)
Пример #34
0
def segwit_multisign(tx,
                     i,
                     script,
                     pk,
                     amount,
                     hashcode=SIGHASH_ALL,
                     separator_index=None):
    wscript = segwit_strip_script_separator(script, index=separator_index)
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       wscript,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), pk)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    return sig
Пример #35
0
def bech32_sign(tx, i, priv, amount, script=None, hashcode=SIGHASH_ALL):
    from bitcoin import deserialize, segwit_signature_form, ecdsa_raw_sign, der_encode_sig, serialize, compress
    i = int(i)
    txobj = tx if isinstance(tx, dict) else deserialize(tx)
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    pub = compress(privkey_to_pubkey(priv))
    script = script or ('76a914' + hash160(binascii.unhexlify(pub)) + '88ac')
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       script,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    txobj['ins'][i]['txinwitness'] = [sig, pub]
    return serialize(txobj)
def signup():
    msg = ''
    if request.method == "POST" and 'username' in request.form and 'password' in request.form and 'email' in request.form:
        username = request.form["username"]
        password = request.form["password"]
        email = request.form["email"]
        # Check if account exists using MySQL
        cursor.execute('SELECT * FROM accounts WHERE username = %s',
                       (username, ))
        account = cursor.fetchone()
        # If account exists show error and validation checks
        if account:
            msg = 'Account already exists!'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address!'
        elif not re.match(r'[A-Za-z0-9]+', username):
            msg = 'Username must contain only characters and numbers!'
        elif not username or not password or not email:
            msg = 'Please fill out the form!'
        else:
            # converting password into sha 256 to store
            password = hashlib.sha256(password.encode()).hexdigest()
            # Account doesnt exists and the form data is valid, now insert new account into accounts table
            # To generate new private key
            temp_private_key = bitcoin.random_key()
            (public_key_x, public_key_y) = public_key_gen(temp_private_key)
            # compressing public key Compress public key, adjust prefix depending on whether y is even or odd
            compressed_prefix = '02' if (public_key_y % 2) == 0 else '03'
            public_key_comp = compressed_prefix + \
                (bitcoin.encode(public_key_x, 16).zfill(64))
            cursor.execute(
                'INSERT INTO accounts VALUES (NULL,%s,%s,%s,%s,%s,%s,%s)',
                (username, password, email, "user", str(public_key_x),
                 str(public_key_y), str(public_key_comp)))
            mydb.commit()
            msg = 'You have successfully registered! Your private key is:\n' + temp_private_key
    elif request.method == "POST":
        msg = 'Please fill the form'
    return render_template('signup.html', msg=msg)
Пример #37
0
for i, test in enumerate(mul_tests):
    print 'trying mul_test %i' % i, test
    o1 = substitutes.jacobian_mul_substitute(*test)
    o2 = s.profile(t.k0, c, 0, funid=0, abi=test)
    # assert o1["gas"] == o2["gas"], (o1, o2, test)
    assert o1["output"] == o2["output"], (o1, o2, test)

c = s.contract('ecrecover.se')
print "Starting ecrecover tests"

for i in range(5):
    print 'trying ecrecover_test', vals[i*2], vals[i*2+1]
    k = vals[i*2]
    h = vals[i*2+1]
    V, R, S = b.ecdsa_raw_sign(b.encode(h, 256, 32), k)
    aa = time.time()
    o1 = substitutes.ecrecover_substitute(h, V, R, S)
    print 'sub', time.time() - aa
    a = time.time()
    o2 = s.profile(t.k0, c, 0, funid=0, abi=[h, V, R, S])
    print time.time() - a
    # assert o1["gas"] == o2["gas"], (o1, o2, h, V, R, S)
    assert o1["output"] == o2["output"], (o1, o2, h, V, R, S)

# Explicit tests

data = [[
    0xf007a9c78a4b2213220adaaf50c89a49d533fbefe09d52bbf9b0da55b0b90b60,
    0x1b,
    0x5228fc9e2fabfe470c32f459f4dc17ef6a0a81026e57e4d61abc3bc268fc92b5,
Пример #38
0
	    to_be_hashed += btc.encode_pubkey(kGend,'bin_compressed')	
	    
	#note that e[i][0] is calculated as a borromean hash of e0, it is not equal to e0
	to_be_hashed += M
	e0 = sha256(to_be_hashed).digest()
	for i in range(len(vks)):
	    e[i][0] = borr_hash(M,e0,i,0,is_pubkey=False)
	#continue processing for all vertices after the 0-th, up
	#to the signing index.
	for i,loop in enumerate(vks):
	    for x in range(1,signing_indices[i]+1):
		y, s[i][x-1] = get_kG(e[i][x-1],vks[i][x-1])
		e[i][x] = borr_hash(M,y,i,x)
	    #finally, set the signature at the signing index using the privkey
	    s[i][signing_indices[i]] = \
		btc.encode((btc.decode(k[i],256) - \
		(btc.decode(sks[i],256))*(btc.decode(e[i][signing_indices[i]],256)))%btc.N, 256)
	final_sig = encode_sig(e0,s)
	if options.write_sig_file:
	    print 'writing sig to file: '+options.write_sig_file
	    print 'signature length: '+str(len(final_sig))
	    with open(options.write_sig_file,'wb') as f:
		f.write(final_sig)
    else:
	#verify operation
	#as noted in the paper, this operation is much simpler
	#than signing as we don't treat the signing index as distinct.
	#Because we don't know it!
	with open(options.read_sig_file,'rb') as f:
	    sig = f.read()
	fmt = 'hex' if options.message_file else 'bin'
	received_sig = decode_sig(sig, vks, fmt=fmt)
Пример #39
0
def test_saveload():
    s = tester.state()
    c = s.abi_contract(saveload_code)
    o = c.kall()
    assert o[0] == 0x73697220626f62616c6f7420746f207468652072657363756520212131213121, bitcoin.encode(o[0], 16)
    assert o[1] == 0x2131213100000000000000000000000000000000000000000000000000000000, bitcoin.encode(o[1], 16)
    assert o[2] == 0x73697220626f62616c6f7420746f207468652072657363756520212131213121, bitcoin.encode(o[2], 16)
    assert o[3] == 0x2131213100000000000000000000000000000000000000000000000000000000, bitcoin.encode(o[3], 16)
    assert o[4] == 0x73697220626f62616c6f7420746f207468652072657363756520212131213121, bitcoin.encode(o[4], 16)
    assert o[5] == 0x2100000000000000000000000000000000000000000000000000000000000000, bitcoin.encode(o[5], 16)
import bitcoin

valid_private_key = False
while not valid_private_key:
    private_key = bitcoin.random_key()
    decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
    valid_private_key = 0 < decoded_private_key < bitcoin.N
    print("Private key in hexadecimal is {}".format(private_key))
    print("Private key in decimal is {}".format(decoded_private_key))
wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
print("Private key in WIF is {}".format(wif_encoded_private_key))
compressed_private_key = private_key + '01'
print("Private key compressed in hexadecimal {}".format(compressed_private_key))
wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
print("Private key WIF compressed is {}".format(wif_compressed_private_key))
public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
print("Public key (x,y) coordinates is".format(public_key))
hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex')
print("Hex encoded public key is {}".format(hex_encoded_public_key))
(public_key_x, public_key_y) = public_key
if (public_key_y % 2) == 0:
    compressed_prefix = '02'
else:
    compressed_prefix = '03'
hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
print("Compressed Public Key (hex) is {}".format(hex_compressed_public_key))
print("Bitcoin Address (b58check) is {}".format(bitcoin.pubkey_to_address(public_key)))
print("Compressed Bitcoin Address (b58check) is: {}".format(bitcoin.pubkey_to_address(hex_compressed_public_key)))
Пример #41
0
 def base_encoder_tests(self):
   self.assertEqual(b.encode(1029,256),'\x04\x05')
   self.assertEqual(b.decode('DEADBEEF',16),3735928559)
   r = random.randrange(2**256)
   self.assertEqual(b.decode(b.changebase(b.encode(r,16),16,58),58),r)
   self.assertEqual(b.base58export(b.base58check(r,101,34)),r)
Пример #42
0
def hamming_weight(n):
    return len([x for x in b.encode(n, 2) if x == '1'])
Пример #43
0
def binary_length(n):
    return len(b.encode(n, 2))
Пример #44
0
def _encode_sig(v, r, s):
    assert isinstance(v, (int, long))
    assert v in (27, 28)
    vb, rb, sb = chr(v - 27), bitcoin.encode(r, 256), bitcoin.encode(s, 256)
    return lzpad32(rb) + lzpad32(sb) + vb
Пример #45
0
def make_id(description, *ints):
    return sha3(''.join(encode(i,256).rjust(32,'\x00')for i in ints)+description).digest()
Пример #46
0
def test_saveload2():
    s = tester.state()
    c = s.contract(saveload_code2)
    s.send(tester.k0, c, 0)
    assert bitcoin.encode(s.block.get_storage_data(c, 0), 256) == b'01ab' + b'\x00' * 28
    assert bitcoin.encode(s.block.get_storage_data(c, 1), 256) == b'01ab' + b'\x00' * 28