示例#1
0
 def __init__(self, pubkey, privkey):
     """The address object consists of the public key and
     private key.
     """
     # validate that the keys correspond to the correct network
     if a2b_base58(pubkey)[0] != self.PUBLIC_KEY_PREFIX:
         raise InvalidAddressError("%s is not a public key for %s" %
                                   (pubkey, self.__class__.__name__))
     elif a2b_base58(privkey)[0] != self.PRIVATE_KEY_PREFIX:
         raise InvalidAddressError("%s is not a private key for %s" %
                                   (privkey, self.__class__.__name__))
     else:
         self.pubkey = pubkey
         self.privkey = privkey
示例#2
0
 def rawPubkey(self):
     """Returns the raw public key associated with this address.
     This is a raw 32-byte string with no checksums
     """
     # note the first byte determines what type of address
     #  and the last four are checksums
     return a2b_base58(self.pubkey)[1:-4]
示例#3
0
    def __init__(self, address):
        super().__init__()
        self.address = address if type(address) is bytes else a2b_base58(address)

        self._extra_bytes = self.address
        self._args = [self.address]

        validate_address(self.address)
示例#4
0
文件: empower.py 项目: XertroV/nvblib
    def __init__(self, votes, address):
        super().__init__()
        self.address = _to_bytes(lambda a: a2b_base58(a), address)
        self.votes = _to_bytes(lambda v: int(v).to_bytes(4, ENDIAN), votes)
        self._extra_bytes = self.votes + self.address
        self._args = [self.votes, self.address_pretty()]

        validate_address(self.address)
示例#5
0
    def __init__(self, address, categories):
        super().__init__()
        self.address = _to_bytes(lambda a: a2b_base58(a), address)
        self.categories = _to_bytes(lambda c: int(c).to_bytes(1, ENDIAN), categories)
        self._extra_bytes = self.categories + self.address
        self._args = [self.categories, self.address_pretty()]

        validate_address(self.address)
示例#6
0
    def test_transfer(self):
        enable_transfer_encoded = b'NVB' + transfer.EnableTransfer.OP_CODE + b'\x00\x0c\x9b\nJ\xf3[\xc1(\x1a\xf3\xd5\x13z\x1c\x90\xdc\x11\x17\xb3\x10\x82y\xe0\xf3'
        assert enable_transfer_encoded == transfer.EnableTransfer(a2b_base58('129eqgh8CNi7LibSmJtbDEnZFTmKA6H3HU')).to_bytes()

        disable_transfer_encoded = b'NVB' + transfer.DisableTransfer.OP_CODE
        assert disable_transfer_encoded == transfer.DisableTransfer().to_bytes()

        transfer_encoded = b'NVB' + transfer.TransferIdentity.OP_CODE
        assert transfer_encoded == transfer.TransferIdentity().to_bytes()
示例#7
0
文件: tally.py 项目: XertroV/nvbtally
        def apply(op, nulldata):
            self.session.commit()  # commit to begin with so we know there's nothing in the transaction as we'll be rolling back
            try:
                op_type = type(op)
                if self.network_settings is None and op_type == CreateNetwork:
                    print(network_name, op.name, admin_address, a2b_base58(nulldata.address))
                    self._assert(op.name == network_name, 'network name must match during creation')
                    self._assert(a2b_base58(nulldata.address) == admin_address, 'admin address must match during creation')
                    self.session.add(NetworkSettings(admin_address=nulldata.address, network_name=network_name))
                    self.session.commit()
                    self.reset_network_settings()
                    self._assert(self.network_settings is not None, 'Network settings sanity check failed')
                elif self.network_settings is not None and op_type != CreateNetwork:
                    resolve_if_earlier_than(nulldata.timestamp, commit=False)  # resolve any resolutions that are in the past an unresolved, do not commit as if this tx is not valid the resolution should not be processed!

                    # this is the main operation centre
                    if op_type == CastVote:
                        self.op_cast_vote(op, nulldata)
                    elif op_type == EmpowerVote:
                        self.op_empower_vote(op, nulldata)
                    elif op_type == DelegateVote:
                        self.op_delegate_vote(op, nulldata)
                    elif op_type == ModResolution:
                        self.op_mod_resolution(op, nulldata)
                    elif op_type == EnableTransfer:
                        self.op_enable_transfer(op, nulldata)
                    elif op_type == DisableTransfer:
                        self.op_disable_transfer(op, nulldata)
                    elif op_type == TransferIdentity:
                        self.op_transfer(op, nulldata)
                else:
                    raise Exception('Wrong time for instruction')
                self.session.commit()  # if we get to the end commit
                print('Success:', op.decode(), 'committed')
            except Exception as e:
                print('Failed:', op.decode(), e.__class__, e)
            finally:
                # if something is wrong do not commit, if we already commit()'d this does nothing
                self.session.rollback()
示例#8
0
 def validate_bitcoin_address(self, address):
     bcbytes = a2b_base58(str(address))
     return bcbytes[-4:] == sha256(sha256(
         bcbytes[:-4]).digest()).digest()[:4]
 def do_test(as_text, as_bin):
     self.assertEqual(as_bin, encoding.a2b_base58(as_text))
     self.assertEqual(as_text, encoding.b2a_base58(as_bin))
示例#10
0
 def do_test(as_text, as_bin):
     self.assertEqual(as_bin, encoding.a2b_base58(as_text))
     self.assertEqual(as_text, encoding.b2a_base58(as_bin))
示例#11
0
文件: tally.py 项目: XertroV/nvbtally
from sqlalchemy import desc

from pycoin.encoding import a2b_base58

from nvblib import instruction_lookup, op_code_lookup, get_op
from nvblib import CreateNetwork, CastVote, DelegateVote, EmpowerVote, ModResolution, EnableTransfer, DisableTransfer, TransferIdentity
from nvblib.constants import ENDIAN

from .models import engine, Nulldata, FilteredNulldata, RawVote, Vote, ProcessedVote, Resolution, ValidVoter, NetworkSettings, Delegate, TransferEnabled, Transfers, tally_tables

import logging

logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.ERROR)

admin_default = a2b_base58('13MRso7BA6AxEye7PrfT6TdzVHXLZ2DCD5')
name_default = b'\x04test'


class Tallier:

    def __init__(self):
        self.Session = sessionmaker(bind=engine)
        self.session = self.Session()
        self.network_settings = None
        self.reset_network_settings()

    def reset_db(self):
        for table in tally_tables:
            engine.execute("DROP TABLE %s" % table.__tablename__)
            print("Dropping %s" % table.__tablename__)
示例#12
0
    def doit(num_ins, num_outs, master_xpub=None, subpath="0/%d", fee=10000,
                invals=None, outvals=None, segwit_in=False, outstyles=['p2pkh'], psbt_hacker=None,
                change_outputs=[], capture_scripts=None, add_xpub=None):
        psbt = BasicPSBT()
        txn = Tx(2,[],[])
        master_xpub = master_xpub or simulator_fixed_xprv
        
        # we have a key; use it to provide "plausible" value inputs
        mk = BIP32Node.from_wallet_key(master_xpub)
        xfp = mk.fingerprint()

        psbt.inputs = [BasicPSBTInput(idx=i) for i in range(num_ins)]
        psbt.outputs = [BasicPSBTOutput(idx=i) for i in range(num_outs)]

        for i in range(num_ins):
            # make a fake txn to supply each of the inputs
            # - each input is 1BTC

            # addr where the fake money will be stored.
            subkey = mk.subkey_for_path(subpath % i)
            sec = subkey.sec()
            assert len(sec) == 33, "expect compressed"
            assert subpath[0:2] == '0/'

            psbt.inputs[i].bip32_paths[sec] = xfp + pack('<II', 0, i)

            # UTXO that provides the funding for to-be-signed txn
            supply = Tx(2,[TxIn(pack('4Q', 0xdead, 0xbeef, 0, 0), 73)],[])

            scr = bytes([0x76, 0xa9, 0x14]) + subkey.hash160() + bytes([0x88, 0xac])

            supply.txs_out.append(TxOut(1E8 if not invals else invals[i], scr))

            with BytesIO() as fd:
                if not segwit_in:
                    supply.stream(fd)
                    psbt.inputs[i].utxo = fd.getvalue()
                else:
                    supply.txs_out[-1].stream(fd)
                    psbt.inputs[i].witness_utxo = fd.getvalue()

            spendable = TxIn(supply.hash(), 0)
            txn.txs_in.append(spendable)


        for i in range(num_outs):
            # random P2PKH
            if not outstyles:
                style = ADDR_STYLES[i % len(ADDR_STYLES)]
            else:
                style = outstyles[i % len(outstyles)]

            if i in change_outputs:
                scr, act_scr, isw, pubkey, sp = make_change_addr(mk, style)
                psbt.outputs[i].bip32_paths[pubkey] = sp
            else:
                scr = act_scr = fake_dest_addr(style)
                isw = ('w' in style)

            assert scr
            act_scr = act_scr or scr

            if isw:
                psbt.outputs[i].witness_script = scr
            elif style.endswith('sh'):
                psbt.outputs[i].redeem_script = scr

            if not outvals:
                h = TxOut(round(((1E8*num_ins)-fee) / num_outs, 4), act_scr)
            else:
                h = TxOut(outvals[i], act_scr)

            if capture_scripts is not None:
                capture_scripts.append( act_scr )

            txn.txs_out.append(h)

        with BytesIO() as b:
            txn.stream(b)
            psbt.txn = b.getvalue()

        if add_xpub:
            # some people want extra xpub data in their PSBTs
            from pycoin.encoding import a2b_base58
            psbt.xpubs = [ (a2b_base58(master_xpub),  xfp) ]

        # last minute chance to mod PSBT object
        if psbt_hacker:
            psbt_hacker(psbt)

        rv = BytesIO()
        psbt.serialize(rv)
        assert rv.tell() <= MAX_TXN_LEN, 'too fat'

        return rv.getvalue()
    pubkey_hashed, address_prefix=my_pubaddr_prefix)
assert (addr_uncompressed == pubkey_addr)

print("Bitcoin    Address: ", addr_compressed)
print("      uncompressed: ", addr_uncompressed)
assert (encoding.is_valid_bitcoin_address(
    addr_compressed, allowable_prefixes=my_pubaddr_prefix))
assert (encoding.is_valid_bitcoin_address(
    addr_uncompressed, allowable_prefixes=my_pubaddr_prefix))
print()

## Uncompressed public key
pubkey_bytes = encoding.public_pair_to_sec(pubkey_pair, False)
# uncompressed
pubkey_b58 = encoding.b2a_base58(pubkey_bytes)
assert (pubkey_bytes == encoding.a2b_base58(pubkey_b58))

btc_addr = CBitcoinAddress.from_bytes(
    pubkey_bytes, bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'])
assert (b2h(cec_key.get_pubkey()) == b2h(btc_addr.to_bytes()))
assert (hexlify(cec_key.get_pubkey()) == hexlify(pubkey_bytes))

#print("Uncompressed public key")
c_pubkey = CPubKey(pubkey_bytes)
#print("Is public key valid? ", c_pubkey.is_valid, ", compressed? ", c_pubkey.is_compressed)
assert (c_pubkey.is_compressed == False)
assert (c_pubkey.is_valid == True)

#print("Public Key base58:", pubkey_b58)
#print("           hashed:", encoding.b2a_hashed_base58(pubkey_bytes))
示例#14
0
 def validate_bitcoin_address(self, address):
     bcbytes = a2b_base58(str(address))
     return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
示例#15
0
longest_match = 0
for i1 in '4':  # sure
    for i2 in '2':  # sure
        for i3 in '6':  # sure
            for i4 in '123456789':  # NOT sure
                for i6 in '123456789':  # NOT sure
                    for i7 in '123456789':  # NOT sure

                        # make candidate private key
                        key = k1 + i1 + k2 + i2 + k3 + i3 + k4 + i4 + k5 + i3 + k6 + i6 + k7 + i7 + k8
                        print('Trying {}...\t'.format(key), end='')

                        # the private key encoded in base58 contains also a checksum at the end to check validity
                        # when a candidate key is made by concatenation as above it will most likely not be valid
                        # so we correct the checksum and compression byte of the candidate key
                        data = a2b_base58(key)
                        data, the_hash = data[:-4], data[-4:]
                        data = data[:-1] + b'\01'
                        fixed_key = b2a_base58(data + double_sha256(data)[:4])

                        # calculate the P2SH SegWit address for this private key
                        k = Key.from_text(fixed_key)
                        p2sh = p2sh_address(k)
                        print('{}\t'.format(p2sh), end='')

                        # compare with the published public key
                        if p2sh[0:7] == '37CSnmm':
                            print('Bingo!')
                            exit(0)
                        else:
                            i = 0