def test_invalid_address(self):
     """Test whether invalid addresses fail to decode."""
     for test in INVALID_ADDRESS:
         witver, _ = segwit_addr.decode("bc", test)
         self.assertIsNone(witver)
         witver, _ = segwit_addr.decode("tb", test)
         self.assertIsNone(witver)
 def test_valid_address(self):
     """Test whether valid addresses decode to the correct output."""
     for (address, hexscript) in VALID_ADDRESS:
         hrp = "bc"
         witver, witprog = segwit_addr.decode(hrp, address)
         if witver is None:
             hrp = "tb"
             witver, witprog = segwit_addr.decode(hrp, address)
         self.assertIsNotNone(witver)
         scriptpubkey = segwit_scriptpubkey(witver, witprog)
         self.assertEqual(scriptpubkey, binascii.unhexlify(hexscript))
         addr = segwit_addr.encode(hrp, witver, witprog)
         self.assertEqual(address.lower(), addr)
Example #3
0
def P2WSH(witnessScript):
    # witnessScript for P2WSH is special, be careful.
    dec = None

    if witnessScript.startswith("bc"):
        dec = decode("bc", witnessScript)

    elif witnessScript.startswith("tb"):
        dec = decode("tb", witnessScript)

    if dec:
        return hexlify(bytes.fromhex('0020') + bytes(dec[1]))

    pk_added_code = bytes.fromhex('0020') + sha256(
        bytes.fromhex(witnessScript)).digest()
    return hexlify(pk_added_code)
Example #4
0
def P2WPKH(value):
    dec = None

    if value.startswith("bc"):
        dec = decode("bc", value)

    elif value.startswith("tb"):
        dec = decode("tb", value)

    if dec:
        return hexlify(bytes.fromhex('0014') + bytes(dec[1]))

    pk_added_code = bytes.fromhex('0014') + hashlib.new(
        "ripemd",
        sha256(bytes.fromhex(value)).digest()).digest()
    return hexlify(pk_added_code)
Example #5
0
def elm_nosig(command_set,
              text,
              dest_addr,
              coeff=10,
              len_offset=100,
              final_amount=1000):
    payto = command_set['payto']
    broadcast = command_set['broadcast']

    pref = dest_addr[:2]

    script = putPushdata(b"", text.encode()) + b"\x75\x51"
    init_amount = coeff * (len(script) + len_offset) + final_amount

    dest_script = segwit_addr.encode(pref, 0, el.sha256(script))

    tx1 = payto(dest_script, init_amount * 0.00000001)['hex']

    print("Transaction sending... " + tx1)
    time.sleep(10)
    tx1_hash = broadcast(tx1)

    dest_addr_bytes = bytes(segwit_addr.decode(pref, dest_addr)[1])

    tx1_parse = el.getTransaction(bytes.fromhex(tx1))[1]

    target_out = list(
        filter(lambda x: x.script == b'\x00\x20' + el.sha256(script),
               tx1_parse.txouts))[0]

    target_out_index = list.index(tx1_parse.txouts, target_out)

    tx2_parse = el.TransactionSegwit(
        2, 0, 1,
        [el.Txin(bytes.fromhex(tx1_hash), target_out_index, b'', 0xFFFFFFFF)],
        [el.Txout(final_amount, b'\x00\x14' + dest_addr_bytes)], [[script]], 0)

    tx2 = el.putTransaction(b'', tx2_parse).hex()

    print("Transaction sending... " + tx2)
    time.sleep(10)
    broadcast(tx2)
Example #6
0
def address_to_script(addr):
    witver, witprog = segwit_addr.decode(NetworkConstants.SEGWIT_HRP, addr)
    if witprog is not None:
        assert (0 <= witver <= 16)
        OP_n = witver + 0x50 if witver > 0 else 0
        script = bh2u(bytes([OP_n]))
        script += push_script(bh2u(bytes(witprog)))
        return script
    addrtype, hash_160 = b58_address_to_hash160(addr)
    if addrtype == NetworkConstants.ADDRTYPE_P2PKH:
        script = '76a9'  # op_dup, op_hash_160
        script += push_script(bh2u(hash_160))
        script += '88ac'  # op_equalverify, op_checksig
    elif addrtype == NetworkConstants.ADDRTYPE_P2SH:
        script = 'a9'  # op_hash_160
        script += push_script(bh2u(hash_160))
        script += '87'  # op_equal
    else:
        raise BaseException('unknown address type')
    return script
Example #7
0
def is_valid_syscoin_address(address, network='mainnet'):

    # bech32
    try:
        syscoin_hrp = "tsys" if network == 'testnet' else "sys"
        witver, _ = segwit_addr.decode(syscoin_hrp, address)
        if witver is not None:
            return True
    except:
        address_version = None

    # Only public key addresses are allowed
    # A valid address is a RIPEMD-160 hash which contains 20 bytes
    # Prior to base58 encoding 1 version byte is prepended and
    # 4 checksum bytes are appended so the total number of
    # base58 encoded bytes should be 25.  This means the number of characters
    # in the encoding should be about 34 ( 25 * log2( 256 ) / log2( 58 ) ).

    # Support syscoin address (T-address on testnet and S-address on mainnet)
    syscoin_version = 65 if network == 'testnet' else 63

    # Check length (This is important because the base58 library has problems
    # with long addresses (which are invalid anyway).
    if ((len(address) < 26) or (len(address) > 35)):
        return False

    address_version = None

    try:
        decoded = base58.b58decode_chk(address)
        address_version = ord(decoded[0:1])
    except:
        # rescue from exception, not a valid Syscoin address
        return False

    if (address_version != syscoin_version):
        return False

    return True
Example #8
0
def address_to_script(addr, *, net=None):
    if net is None:
        net = constants.net
    witver, witprog = segwit_addr.decode(net.SEGWIT_HRP, addr)
    if witprog is not None:
        if not (0 <= witver <= 16):
            raise BitcoinException(
                'impossible witness version: {}'.format(witver))
        OP_n = witver + 0x50 if witver > 0 else 0
        script = bh2u(bytes([OP_n]))
        script += push_script(bh2u(bytes(witprog)))
        return script
    addrtype, hash_160 = b58_address_to_hash160(addr)
    if addrtype == net.ADDRTYPE_P2PKH:
        script = '76a9'  # op_dup, op_hash_160
        script += push_script(bh2u(hash_160))
        script += '88ac'  # op_equalverify, op_checksig
    elif addrtype == net.ADDRTYPE_P2SH:
        script = 'a9'  # op_hash_160
        script += push_script(bh2u(hash_160))
        script += '87'  # op_equal
    else:
        raise BitcoinException('unknown address type: {}'.format(addrtype))
    return script
Example #9
0
def is_valid_bech32(v):
    '''Check vector v for bech32 validity'''
    for hrp in ['sum', 'tsum', 'rsum']:
        if decode(hrp, v) != (None, None):
            return True
    return False
from segwit_addr import encode
from segwit_addr import decode
from hash_util   import hash160,hash256

hrp='tb' #testnet
#hrp='bc' #mainnet

pubkey1='21026ccfb8061f235cc110697c0bfb3afb99d82c886672f6b9b5393b25a434c0cbf3'
pubkey2='2103befa190c0c22e2f53720b1be9476dcf11917da4665c44c9c71c3a2d28a933c35'
pubkey3='2102be46dc245f58085743b1cc37c82f0d63a960efa43b5336534275fc469b49f4ac'
data='52'+pubkey1+pubkey2+pubkey3+'53'+'ae'
script_hash=hash256(data.decode('hex')).encode('hex')

witver=0
witprog=[int(x) for x in bytearray.fromhex(script_hash)]
#print witprog
address=encode(hrp, witver, witprog)
print address
data=decode(hrp, address)
#print data


Example #11
0
def is_segwit_address(addr):
    try:
        witver, witprog = segwit_addr.decode(NetworkConstants.SEGWIT_HRP, addr)
    except Exception as e:
        return False
    return witprog is not None
def is_valid_bech32(v):
    '''Check vector v for bech32 validity'''
    for hrp in ['bc', 'tb', 'bcrt']:
        if decode(hrp, v) != (None, None):
            return True
    return False
Example #13
0
def elm_sig(command_set,
            text,
            dest_addr,
            coeff=10,
            len_offset=100,
            final_amount=1000):
    payto = command_set['payto']
    broadcast = command_set['broadcast']
    createnewaddress = command_set['createnewaddress']
    getprivatekeys = command_set['getprivatekeys']

    pref = dest_addr[:2]

    tmp_addr = createnewaddress()

    tmp_addr_bytes = bytes(segwit_addr.decode(pref, tmp_addr)[1])

    script = el.putPushdata(
        b"",
        text.encode()) + b"\x75\x76\xA9\x14" + tmp_addr_bytes + b"\x88\xAC"
    init_amount = coeff * (len(script) + len_offset) + final_amount

    dest_script = segwit_addr.encode(pref, 0, el.sha256(script))

    tx1 = payto(dest_script, init_amount * 0.00000001)['hex']

    print("Transaction sending... " + tx1)
    time.sleep(10)
    tx1_hash = broadcast(tx1)

    dest_addr_bytes = bytes(segwit_addr.decode(pref, dest_addr)[1])

    tx1_parse = el.getTransaction(bytes.fromhex(tx1))[1]

    target_out = list(
        filter(lambda x: x.script == b'\x00\x20' + el.sha256(script),
               tx1_parse.txouts))[0]

    target_out_index = list.index(tx1_parse.txouts, target_out)

    hashtype = el.SIGHASH_ALL

    tx2_in = [
        el.Txin(bytes.fromhex(tx1_hash), target_out_index, b'', 0xFFFFFFFF)
    ]
    tx2_out = [el.Txout(final_amount, b'\x00\x14' + dest_addr_bytes)]

    tx2_parse = el.TransactionSegwit(2, 0, 1, tx2_in, tx2_out, [[script]], 0)

    txdigest = el.witness_digest(tx2_parse, hashtype, 0, init_amount,
                                 b'\x00\x20' + el.sha256(script), script)

    txsign = sign_tx_hash(
        txdigest,
        bitcoin.deserialize_privkey(getprivatekeys(tmp_addr))[1], hashtype)

    tx2_parse_signed = el.TransactionSegwit(2, 0, 1, tx2_in, tx2_out,
                                            [[txsign[1], txsign[0], script]],
                                            0)

    tx2 = el.putTransaction(b'', tx2_parse_signed).hex()

    print("Transaction sending... " + tx2)
    time.sleep(10)
    broadcast(tx2)