Exemple #1
0
 def test1(self):
     hasher = hashlib.sha256()
     hasher.update(b'test case')
     data = hasher.digest()
     self.assertEqual(bytes_to_hexstring(data, reverse=False),
                      '{:064x}'.format(int.from_bytes(data, 'big')))
     self.assertEqual(
         hexstring_to_bytes(bytes_to_hexstring(data, reverse=False),
                            reverse=False), data)
Exemple #2
0
def sendtoaddress(address, amount, memo=''):
    transaction_builder = spv.new_transaction_builder(memo=memo)
    transaction_builder.process_change(pyspv.PubKeyChange)
    transaction_builder.process(get_output_producer(spv, address, spv.coin.parse_money(amount)))
    tx = transaction_builder.finish(shuffle_inputs=True, shuffle_outputs=True)

    if not tx.verify_scripts():
        raise Exception("internal error building transaction")

    spv.broadcast_transaction(tx)

    return {
        'tx': pyspv.bytes_to_hexstring(tx.serialize(), reverse=False),
        'hash': pyspv.bytes_to_hexstring(tx.hash()),
    }
Exemple #3
0
def main():
    # We need a wallet, but don't need a network. Set peer_goal to 0
    spv = pyspv.pyspv('pyspv-simple-wallet',
                      logging_level=pyspv.INFO,
                      peer_goal=0,
                      listen=None)

    tx, _ = pyspv.transaction.Transaction.unserialize(
        pyspv.hexstring_to_bytes(sys.argv[1], reverse=False), spv.coin)
    input_count = len(tx.inputs)
    total_added = 0

    for spend_hash in sys.argv[2:]:
        spend_hash = pyspv.hexstring_to_bytes(spend_hash)
        spend = spv.wallet.spends[spend_hash]['spend']

        for input_creator in spend.create_input_creators(
                spv, pyspv.transaction.Transaction.SIGHASH_ALL
                | pyspv.transaction.Transaction.SIGHASH_ANYONECANPAY):
            tx.inputs.append(
                pyspv.transaction.UnsignedTransactionInput(input_creator))

        total_added += spend.amount

    for i, unsigned_input in enumerate(tx.inputs):
        if isinstance(unsigned_input,
                      pyspv.transaction.UnsignedTransactionInput):
            tx.inputs[i] = unsigned_input.sign(tx, i)

    print(pyspv.bytes_to_hexstring(tx.serialize(), reverse=False))
    print("total added as inputs: {}".format(
        spv.coin.format_money(total_added)))

    spv.shutdown()  # Async shutdown
    spv.join()  # Wait for shutdown to complete
Exemple #4
0
def sendtoaddress(address, amount, memo=''):
    transaction_builder = spv.new_transaction_builder(memo=memo)
    transaction_builder.process_change(pyspv.PubKeyChange)
    transaction_builder.process(
        get_output_producer(spv, address, spv.coin.parse_money(amount)))
    tx = transaction_builder.finish(shuffle_inputs=True, shuffle_outputs=True)

    if not tx.verify_scripts():
        raise Exception("internal error building transaction")

    spv.broadcast_transaction(tx)

    return {
        'tx': pyspv.bytes_to_hexstring(tx.serialize(), reverse=False),
        'hash': pyspv.bytes_to_hexstring(tx.hash()),
    }
Exemple #5
0
def main():
    # We need a wallet, but don't need a network. Set peer_goal to 0
    spv = pyspv.pyspv('pyspv-simple-wallet', logging_level=pyspv.INFO, peer_goal=0, listen=None)

    tx, _ = pyspv.transaction.Transaction.unserialize(pyspv.hexstring_to_bytes(sys.argv[1], reverse=False), spv.coin)
    input_count = len(tx.inputs)
    total_added = 0

    for spend_hash in sys.argv[2:]:
        spend_hash = pyspv.hexstring_to_bytes(spend_hash)
        spend = spv.wallet.spends[spend_hash]['spend']

        for input_creator in spend.create_input_creators(spv, pyspv.transaction.Transaction.SIGHASH_ALL | pyspv.transaction.Transaction.SIGHASH_ANYONECANPAY):
            tx.inputs.append(pyspv.transaction.UnsignedTransactionInput(input_creator))

        total_added += spend.amount

    for i, unsigned_input in enumerate(tx.inputs):
        if isinstance(unsigned_input, pyspv.transaction.UnsignedTransactionInput):
            tx.inputs[i] = unsigned_input.sign(tx, i)

    print(pyspv.bytes_to_hexstring(tx.serialize(), reverse=False))
    print("total added as inputs: {}".format(spv.coin.format_money(total_added)))

    spv.shutdown() # Async shutdown
    spv.join()     # Wait for shutdown to complete
Exemple #6
0
    def f(spend):
        r = {
            'id': pyspv.bytes_to_hexstring(spend.hash()),
            'class': spend.__class__.__name__,
            'amount': spv.coin.format_money(spend.amount),
            'confirmations': spend.get_confirmations(spv),
        }

        if hasattr(spend, 'prevout'):
            r['prevout'] = {
                'txid': pyspv.bytes_to_hexstring(spend.prevout.tx_hash),
                'n': spend.prevout.n
            }

        if hasattr(spend, 'address'):
            r['address'] = spend.address

        return r
Exemple #7
0
    def f(spend):
        r = {
            'id': pyspv.bytes_to_hexstring(spend.hash()),
            'class': spend.__class__.__name__,
            'amount': spv.coin.format_money(spend.amount),
            'confirmations': spend.get_confirmations(spv),
        }

        if hasattr(spend, 'prevout'):
            r['prevout'] = {
                'txid': pyspv.bytes_to_hexstring(spend.prevout.tx_hash),
                'n'   : spend.prevout.n
            }

        if hasattr(spend, 'address'):
            r['address'] = spend.address

        return r
Exemple #8
0
def genmultisig(nreq, mtotal, *pubkeys):
    '''Generate a new multisignature address and redemption script that requires `nreq' signatures to spend and provides a possible `mtotal'.
    If public keys are provided on the command line, those are used instead of generating new ones.'''

    nreq = int(nreq)
    mtotal = int(mtotal)
    pubkeys = list(pubkeys)
    assert 0 <= nreq <= mtotal
    assert len(pubkeys) <= mtotal

    # Create new keys if necessary
    while len(pubkeys) < mtotal:
        pk = pyspv.keys.PrivateKey.create_new()
        spv.wallet.add('private_key', pk, {'label': ''})
        pubkeys.append(pk.get_public_key(compressed=True).as_hex())

    pubkeys = [pyspv.keys.PublicKey.from_hex(pubkey) for pubkey in pubkeys]
    pubkeys.sort()

    # build the M-of-N multisig redemption script and add it to the wallet
    # (the p2sh monitor will notice that we added a redemption script to the
    # wallet and start watching for transactions to it

    script = pyspv.script.Script()
    script.push_int(nreq)

    for pubkey in pubkeys:
        script.push_bytes(pubkey.pubkey)

    script.push_int(len(pubkeys))
    script.push_op(pyspv.script.OP_CHECKMULTISIG)

    redemption_script = script.program
    address = pyspv.base58_check(
        spv.coin,
        spv.coin.hash160(redemption_script),
        version_bytes=spv.coin.P2SH_ADDRESS_VERSION_BYTES)

    try:
        spv.wallet.add('redemption_script', redemption_script, {})
    except pyspv.wallet.DuplicateWalletItem:
        # No worries, we already have this redemption script
        if spv.logging_level <= pyspv.INFO:
            print('[simple-wallet] Duplicate redemption script??')
        pass

    return {
        'address':
        address,
        'redemption_script':
        pyspv.bytes_to_hexstring(redemption_script, reverse=False),
        'pubkeys': [pubkey.as_hex() for pubkey in pubkeys],
        'nreq':
        nreq,
    }
Exemple #9
0
def genmultisig(nreq, mtotal, *pubkeys):
    '''Generate a new multisignature address and redemption script that requires `nreq' signatures to spend and provides a possible `mtotal'.
    If public keys are provided on the command line, those are used instead of generating new ones.'''

    nreq = int(nreq)
    mtotal = int(mtotal)
    pubkeys = list(pubkeys)
    assert 0 <= nreq <= mtotal
    assert len(pubkeys) <= mtotal

    # Create new keys if necessary
    while len(pubkeys) < mtotal:
        pk = pyspv.keys.PrivateKey.create_new()
        spv.wallet.add('private_key', pk, {'label': ''})
        pubkeys.append(pk.get_public_key(compressed=True).as_hex())

    pubkeys = [pyspv.keys.PublicKey.from_hex(pubkey) for pubkey in pubkeys]
    pubkeys.sort()

    # build the M-of-N multisig redemption script and add it to the wallet
    # (the p2sh monitor will notice that we added a redemption script to the 
    # wallet and start watching for transactions to it

    script = pyspv.script.Script()
    script.push_int(nreq)

    for pubkey in pubkeys:
        script.push_bytes(pubkey.pubkey)

    script.push_int(len(pubkeys))
    script.push_op(pyspv.script.OP_CHECKMULTISIG)

    redemption_script = script.program
    address = pyspv.base58_check(spv.coin, spv.coin.hash160(redemption_script), version_bytes=spv.coin.P2SH_ADDRESS_VERSION_BYTES)

    try:
        spv.wallet.add('redemption_script', redemption_script, {})
    except pyspv.wallet.DuplicateWalletItem:
        # No worries, we already have this redemption script
        if spv.logging_level <= pyspv.INFO:
            print('[simple-wallet] Duplicate redemption script??')
        pass

    return {
        'address': address,
        'redemption_script': pyspv.bytes_to_hexstring(redemption_script, reverse=False),
        'pubkeys': [ pubkey.as_hex() for pubkey in pubkeys ],
        'nreq': nreq,
    }
Exemple #10
0
def main():
    bob_key = pyspv.keys.PrivateKey.create_new()
    bob_public_key = bob_key.get_public_key(True)
    print("Bob's public key =", bob_public_key.as_hex())

    # Alice wants to pay Bob. Bob gives Alice his public key. Alice creates a new key and multiplies Bob's public key with her private key and sends her public key to Bob.
    alice_key = pyspv.keys.PrivateKey.create_new()
    alice_public_key = alice_key.get_public_key(True)
    alice_shared_secret_point = bob_public_key.multiply(alice_key.as_int())
    print("Ephemeral key (Bob needs this to redeem) =",
          alice_public_key.as_hex())

    # Phase two is to hash the shared secret
    import hashlib
    hasher = hashlib.sha256()
    hasher.update(alice_shared_secret_point.pubkey)
    shared_secret = hasher.digest()

    print("Shared secret =",
          pyspv.bytes_to_hexstring(shared_secret, reverse=False))

    # We need to add shared_secret to Bob's public key
    new_bob_public_key = bob_public_key.add_constant(
        int.from_bytes(shared_secret, 'big'))
    print("New Bob Public Key =", new_bob_public_key.as_hex())
    print("New Bob Payment Address =",
          new_bob_public_key.as_address(pyspv.Bitcoin))

    # In order to compute the private key to new_bob_public_key, Bob has work to do.  First Bob multiplies the ephemeral key produced by alice by his private key:
    bob_shared_secret_point = alice_public_key.multiply(bob_key.as_int())

    # And hashes it to produce the shared secret
    hasher = hashlib.sha256()
    hasher.update(bob_shared_secret_point.pubkey)
    shared_secret_by_bob = hasher.digest()
    print("Bob figured out the shared secret =",
          shared_secret_by_bob == shared_secret)

    # Bob adds the shared secret to his private key. This works because, given Q=dG, then (d+n)G=dG+nG=Q+nG  (and alice computed Q+nG above and sent money to it, but now we know the private key d+n).
    new_bob_key = bob_key.add_constant(
        int.from_bytes(shared_secret_by_bob, 'big'))
    new_bob_computed_public_key = new_bob_key.get_public_key(True)
    print("Bob figured out the correct private key =",
          new_bob_computed_public_key.pubkey == new_bob_public_key.pubkey)
Exemple #11
0
def main():
    simple_wallet = __import__('simple-wallet')

    # We need a wallet, but don't need a network. Set peer_goal to 0
    spv = pyspv.pyspv('pyspv-simple-wallet', logging_level=pyspv.INFO, peer_goal=0, listen=None)

    tx = pyspv.transaction.Transaction(spv.coin)
    total_output = 0

    for i in range(1, len(sys.argv), 2):
        address = sys.argv[i]
        amount  = sys.argv[i+1]
        
        output_producer = simple_wallet.get_output_producer(spv, address, spv.coin.parse_money(amount))
        for output in output_producer.create_outputs(spv):
            tx.outputs.append(output)
            total_output += output.amount

    print(pyspv.bytes_to_hexstring(tx.serialize(), reverse=False))
    print("total transaction output: {}".format(spv.coin.format_money(total_output)))

    spv.shutdown() # Async shutdown
    spv.join()     # Wait for shutdown to complete
Exemple #12
0
def main():
    bob_key = pyspv.keys.PrivateKey.create_new()
    bob_public_key = bob_key.get_public_key(True)
    print("Bob's public key =", bob_public_key.as_hex())
    
    # Alice wants to pay Bob. Bob gives Alice his public key. Alice creates a new key and multiplies Bob's public key with her private key and sends her public key to Bob.
    alice_key = pyspv.keys.PrivateKey.create_new()
    alice_public_key = alice_key.get_public_key(True)
    alice_shared_secret_point = bob_public_key.multiply(alice_key.as_int())
    print("Ephemeral key (Bob needs this to redeem) =", alice_public_key.as_hex())
    
    # Phase two is to hash the shared secret
    import hashlib
    hasher = hashlib.sha256()
    hasher.update(alice_shared_secret_point.pubkey)
    shared_secret = hasher.digest()
    
    print("Shared secret =", pyspv.bytes_to_hexstring(shared_secret, reverse=False))
    
    # We need to add shared_secret to Bob's public key
    new_bob_public_key = bob_public_key.add_constant(int.from_bytes(shared_secret, 'big'))
    print("New Bob Public Key =", new_bob_public_key.as_hex())
    print("New Bob Payment Address =", new_bob_public_key.as_address(pyspv.Bitcoin))
    
    # In order to compute the private key to new_bob_public_key, Bob has work to do.  First Bob multiplies the ephemeral key produced by alice by his private key:
    bob_shared_secret_point = alice_public_key.multiply(bob_key.as_int())
    
    # And hashes it to produce the shared secret
    hasher = hashlib.sha256()
    hasher.update(bob_shared_secret_point.pubkey)
    shared_secret_by_bob = hasher.digest()
    print("Bob figured out the shared secret =", shared_secret_by_bob == shared_secret)
    
    # Bob adds the shared secret to his private key. This works because, given Q=dG, then (d+n)G=dG+nG=Q+nG  (and alice computed Q+nG above and sent money to it, but now we know the private key d+n).
    new_bob_key = bob_key.add_constant(int.from_bytes(shared_secret_by_bob, 'big'))
    new_bob_computed_public_key = new_bob_key.get_public_key(True)
    print("Bob figured out the correct private key =", new_bob_computed_public_key.pubkey == new_bob_public_key.pubkey)
Exemple #13
0
 def test1(self):
     hasher = hashlib.sha256()
     hasher.update(b'test case')
     data = hasher.digest()
     self.assertEqual(bytes_to_hexstring(data, reverse=False), '{:064x}'.format(int.from_bytes(data, 'big')))
     self.assertEqual(hexstring_to_bytes(bytes_to_hexstring(data, reverse=False), reverse=False), data)
Exemple #14
0
def sendrawtransaction(tx_bytes):
    tx_bytes = pyspv.hexstring_to_bytes(tx_bytes, reverse=False)
    tx, _ = pyspv.transaction.Transaction.unserialize(tx_bytes, spv.coin)
    spv.broadcast_transaction(tx)
    return pyspv.bytes_to_hexstring(tx.hash())
Exemple #15
0
def sendrawtransaction(tx_bytes):
    tx_bytes = pyspv.hexstring_to_bytes(tx_bytes, reverse=False)
    tx, _ = pyspv.transaction.Transaction.unserialize(tx_bytes, spv.coin)
    spv.broadcast_transaction(tx)
    return pyspv.bytes_to_hexstring(tx.hash())