def check_contract(prev_tx, prev_vout, contract_hash, asset):
    a = wally.hex_from_bytes(wally.hex_to_bytes(prev_tx)[::-1])+wally.hex_from_bytes(struct.pack('<L', int(prev_vout)))
    a = wally.hex_from_bytes(wally.sha256d(wally.hex_to_bytes(a)))
    b = a + contract_hash
    merkle = wally.hex_from_bytes(wally.sha256_midstate(wally.hex_to_bytes(b)))
    c = merkle + '0000000000000000000000000000000000000000000000000000000000000000'
    asset_id = wally.hex_from_bytes(wally.sha256_midstate(wally.hex_to_bytes(c))[::-1])
    return(asset_id == asset)
Beispiel #2
0
def get_ga_root_key(testnet):
    """Return the GreenAddress root public key for the given network, or as set by options"""
    key_data = gaconstants.GA_KEY_DATA_TESTNET if testnet else gaconstants.GA_KEY_DATA_MAINNET
    return get_bip32_pubkey(
        wally.hex_to_bytes(key_data['chaincode']),
        wally.hex_to_bytes(key_data['pubkey']),
        testnet
    )
Beispiel #3
0
def sign(txdata, signatories):
    tx = txutil.from_hex(txdata['tx'])
    for i in range(wally.tx_get_num_inputs(tx)):
        script = wally.hex_to_bytes(txdata['prevout_scripts'][i])
        script_type = txdata['prevout_script_types'][i]
        flags, value, sighash = 0, 0, wally.WALLY_SIGHASH_ALL

        if script_type == gaconstants.P2SH_P2WSH_FORTIFIED_OUT:
            flags = wally.WALLY_TX_FLAG_USE_WITNESS
            value = int(txdata['prevout_values'][i])
        preimage_hash = wally.tx_get_btc_signature_hash(
            tx, i, script, value, sighash, flags)

        sigs = [s.get_signature(preimage_hash) for s in signatories]

        if script_type == gaconstants.P2SH_P2WSH_FORTIFIED_OUT:
            txutil.set_witness(
                tx, i, [None, _to_der(sigs[0]),
                        _to_der(sigs[1]), script])
            flags = wally.WALLY_SCRIPT_SHA256 | wally.WALLY_SCRIPT_AS_PUSH
            script = wally.witness_program_from_bytes(script, flags)
        else:
            sigs = sigs[0] + sigs[1]
            script = wally.scriptsig_multisig_from_bytes(
                script, sigs, [sighash, sighash], 0)
        wally.tx_set_input_script(tx, i, script)

    return tx
Beispiel #4
0
    def sign_tx(self, details):
        txdetails = details['transaction']

        utxos = txdetails['used_utxos'] or txdetails['old_used_utxos']
        signatures = []
        for index, utxo in enumerate(utxos):
            wally_tx = wally.tx_from_hex(txdetails['transaction'],
                                         wally.WALLY_TX_FLAG_USE_WITNESS)
            is_segwit = utxo['script_type'] in [14, 15, 159, 162]  # FIXME!!
            if not is_segwit:
                # FIXME
                raise NotImplementedError("Non-segwit input")
            flags = wally.WALLY_TX_FLAG_USE_WITNESS if is_segwit else 0
            prevout_script = wally.hex_to_bytes(utxo['prevout_script'])
            txhash = wally.tx_get_btc_signature_hash(wally_tx, index,
                                                     prevout_script,
                                                     utxo['satoshi'],
                                                     wally.WALLY_SIGHASH_ALL,
                                                     flags)

            path = utxo['user_path']
            privkey = self.get_privkey(path)
            signature = wally.ec_sig_from_bytes(
                privkey, txhash, wally.EC_FLAG_ECDSA | wally.EC_FLAG_GRIND_R)
            signature = wally.ec_sig_to_der(signature)
            signature.append(wally.WALLY_SIGHASH_ALL)
            signatures.append(wally.hex_from_bytes(signature))
            logging.debug('Signature (der) input %s path %s: %s', index, path,
                          signature)

        return json.dumps({'signatures': signatures})
Beispiel #5
0
 def _get_sighash(self, wally_tx, index, utxo):
     flags = wally.WALLY_TX_FLAG_USE_WITNESS
     prevout_script = wally.hex_to_bytes(utxo['prevout_script'])
     if utxo['confidential']:
         value = bytes.fromhex(utxo['commitment'])
     else:
         value = wally.tx_confidential_value_from_satoshi(utxo['satoshi'])
     return wally.tx_get_elements_signature_hash(
         wally_tx, index, prevout_script, value, wally.WALLY_SIGHASH_ALL, flags)
def check_tx(issuance_txid, issuance_vin, asset, explorer):
    if (explorer):
        resp = requests.get(url=explorerURL+issuance_txid, verify=True)
        issuance = resp.json()
        c = issuance['vin'][issuance_vin]['issuance']['asset_entropy'] + '0000000000000000000000000000000000000000000000000000000000000000'
        asset_id = wally.hex_from_bytes(wally.sha256_midstate(wally.hex_to_bytes(c))[::-1])
    else:
        issuance = host.call('getrawtransaction', issuance_txid, 1)
        asset_id = issuance['vin'][issuance_vin]['issuance']['asset']

    return(asset_id == asset)
Beispiel #7
0
def seed_from_mnemonic(mnemonic_or_hex_seed):
    """Return seed, mnemonic given an input string

    mnemonic_or_hex_seed can either be:
    - A mnemonic
    - A hex seed, with an 'X' at the end, which needs to be stripped

    seed will always be returned, mnemonic may be None if a seed was passed
    """
    if mnemonic_or_hex_seed.endswith('X'):
        mnemonic = None
        seed = wally.hex_to_bytes(mnemonic_or_hex_seed[:-1])
    else:
        mnemonic = mnemonic_or_hex_seed
        written, seed = wally.bip39_mnemonic_to_seed512(mnemonic_or_hex_seed, None)
        assert written == wally.BIP39_SEED_LEN_512

    assert len(seed) == wally.BIP39_SEED_LEN_512
    return seed, mnemonic
Beispiel #8
0
def countersign(txdata, private_key):
    GreenAddress = PassiveSignatory(
        wally.hex_to_bytes(txdata['prevout_signatures'][0]))
    user = ActiveSignatory(wally.bip32_key_get_priv_key(private_key))
    return sign(txdata, [GreenAddress, user])
Beispiel #9
0
 def _get_sighash(self, wally_tx, index, utxo):
     flags = wally.WALLY_TX_FLAG_USE_WITNESS
     prevout_script = wally.hex_to_bytes(utxo['prevout_script'])
     return wally.tx_get_btc_signature_hash(
             wally_tx, index, prevout_script, utxo['satoshi'], wally.WALLY_SIGHASH_ALL, flags)
contract = json.dumps(
    {
        'name': name,
        'ticker': ticker,
        'precision': precision,
        'entity': {
            'domain': domain
        },
        'issuer_pubkey': issuer_pubkey,
        'version': version
    },
    separators=(',', ':'),
    sort_keys=True)
contract_hash = wally.hex_from_bytes(wally.sha256(contract.encode('ascii')))
a = wally.hex_from_bytes(
    wally.hex_to_bytes(prev_tx)[::-1]) + wally.hex_from_bytes(
        struct.pack('<L', int(prev_vout)))
a = wally.hex_from_bytes(wally.sha256d(wally.hex_to_bytes(a)))
b = a + contract_hash
merkle = wally.hex_from_bytes(wally.sha256_midstate(wally.hex_to_bytes(b)))
c = merkle + '0000000000000000000000000000000000000000000000000000000000000000'
merkle = wally.hex_from_bytes(
    wally.sha256_midstate(wally.hex_to_bytes(c))[::-1])
res['asset_id'] = merkle
res['contract'] = contract
res['contract_hash'] = contract_hash

# Create the rawissuance transaction
contract_hash_rev = wally.hex_from_bytes(
    wally.hex_to_bytes(contract_hash)[::-1])
rawissue = host_1.call('rawissueasset', funded['hex'],
Beispiel #11
0
import wallycore as wally

h2b = wally.hex_to_bytes
b2h = wally.hex_from_bytes

h2b_rev = lambda h: wally.hex_to_bytes(h)[::-1]
b2h_rev = lambda b: wally.hex_from_bytes(b[::-1])
Beispiel #12
0
        0,  # exponent
        36  # bits
    )

    surjectionproof = wally.asset_surjectionproof(asset_id, abf, generator,
                                                  os.urandom(32), asset_ids_in,
                                                  abfs_in, asset_generators_in)

    wally.tx_add_elements_raw_output(output_tx, script_pubkey, generator,
                                     value_commitment, ephemeral_pubkey,
                                     surjectionproof, rangeproof, 0)
# end-create_outputs

# start-add_fee
BITCOIN = "5ac9f65c0efcc4775e0baec4ec03abdde22473cd3cf33c0419ca290e0751b225"
BITCOIN = wally.hex_to_bytes(BITCOIN)[::-1]

wally.tx_add_elements_raw_output(
    output_tx,
    None,
    bytearray([0x01]) + BITCOIN,
    wally.tx_confidential_value_from_satoshi(fee),
    None,  # nonce
    None,  # surjection proof
    None,  # range proof
    0)
# end-add_fee

# start-sign
vout = 0
prev_txid = wally.tx_get_txid(tx)
Beispiel #13
0
def get_ga_root_key(network):
    """Return the GreenAddress root public key for the given network, or as set by options"""
    key_data = gaconstants.get_ga_key_data(network)
    return get_bip32_pubkey(wally.hex_to_bytes(key_data['chaincode']),
                            wally.hex_to_bytes(key_data['pubkey']), network)
Beispiel #14
0
def issuer(asset_amount, asset_address, token_amount, token_address,
           issuer_pubkey, name, ticker, precision, domain):
    data = {}
    version = 0  # don't change
    blind = False
    feerate = 0.00003000

    asset_amount = int(asset_amount) / 10**(8 - int(precision))
    token_amount = int(token_amount) / 10**(8 - int(precision))

    # Create funded base tx
    base = host.call('createrawtransaction', [], [{'data': '00'}])
    funded = host.call('fundrawtransaction', base, {'feeRate': feerate})

    # Create the contact and calculate the asset id (Needed for asset registry!)
    contract = json.dumps(
        {
            'name': name,
            'ticker': ticker,
            'precision': int(precision),
            'entity': {
                'domain': domain
            },
            'issuer_pubkey': issuer_pubkey,
            'version': version
        },
        separators=(',', ':'),
        sort_keys=True)
    contract_hash = wally.hex_from_bytes(wally.sha256(
        contract.encode('ascii')))
    data['contract'] = contract

    # Create the rawissuance transaction
    contract_hash_rev = wally.hex_from_bytes(
        wally.hex_to_bytes(contract_hash)[::-1])
    rawissue = host.call('rawissueasset', funded['hex'],
                         [{
                             'asset_amount': asset_amount,
                             'asset_address': asset_address,
                             'token_amount': token_amount,
                             'token_address': token_address,
                             'blind': blind,
                             'contract_hash': contract_hash_rev
                         }])

    # Blind the transaction
    blind = host.call('blindrawtransaction', rawissue[0]['hex'], True, [],
                      False)

    # Sign transaction
    signed = host.call('signrawtransactionwithwallet', blind)
    decoded = host.call('decoderawtransaction', signed['hex'])
    data['asset_id'] = decoded['vin'][0]['issuance']['asset']

    # Test transaction
    test = host.call('testmempoolaccept', [signed['hex']])
    if test[0]['allowed'] is True:
        txid = host.call('sendrawtransaction', signed['hex'])
        data['txid'] = txid
        data['registry'] = json.dumps({
            'asset_id': data['asset_id'],
            'contract': json.loads(data['contract'])
        })

    return data
Beispiel #15
0
import argparse
import json
import logging
import sys

import wallycore as wally

b2h = lambda b: wally.hex_from_bytes(b)
h2b = lambda h: wally.hex_to_bytes(h)
b2h_rev = lambda b: b2h(b[::-1])
h2b_rev = lambda h: h2b(h)[::-1]


def err(s):
    logging.error(s)
    sys.exit(1)


def parse_tx_file(file):
    with file as f:
        try:
            return wally.tx_from_hex(
                f.read().strip(), wally.WALLY_TX_FLAG_USE_WITNESS
                | wally.WALLY_TX_FLAG_USE_ELEMENTS)
        except ValueError:
            err("Invalid transaction")


def parse_uint256_hex(h):
    try:
        b = h2b_rev(h)
Beispiel #16
0
def h2b_rev(h):
    return wally.hex_to_bytes(h)[::-1]
Beispiel #17
0
def get_redeem_script(keys):
    """Return a 2of3 multisig redeem script as a hex string"""
    keys = [wally.hex_from_bytes(key) for key in keys]
    logging.debug("get_redeem_script public keys = {}".format(keys))
    return wally.hex_to_bytes("5221{}21{}21{}53ae".format(*keys))
Beispiel #18
0
def _b(h):
    return hex_to_bytes(h)