def convert_raw_tx_to_obj(tx: list, extraData: dict):
    tx_inputs, tx_outputs, tx_witnesses = tx[0][0], tx[0][1], tx[1]
    tx_id, tx_body = pack_raw_txid_and_body(tx)
    inputs, outputs, witnesses = [], [], []
    for inp in tx_inputs:
        types, tagged = inp
        input_tx_id, idx = cbor.loads(tagged.value)
        inputs.append({'type': types, 'txId': input_tx_id.hex(), 'idx': idx})

    for out in tx_outputs:
        address, value = out
        outputs.append({'address': base58.b58encode(cbor.dumps(address)), 'value': value})

    for wit in tx_witnesses:
        types, tagged = wit
        witnesses.append({'type': types, 'sign': cbor.loads(tagged.value)})

    ret = {
        'id': tx_id,
        'inputs': inputs,
        'outputs': outputs,
        'witnesses': witnesses,
        'txBody': tx_body
    }
    ret.update(extraData)

    return ret
示例#2
0
        def deconstruct_address(address: str):
            address_root, addr_attr, address_type = cbor.loads(
                cbor.loads(base58.b58decode(address))[0].value)

            return {
                'address_root': address_root,
                'addr_attr': addr_attr,
                'address_type': address_type
            }
示例#3
0
 def test_badread(self):
     try:
         loads(b'\xff')
         assert False, 'badread should have failed'
     except ValueError as ve:
         #logger.info('error', exc_info=True)
         pass
     except Exception as ex:
         print('unexpected error!', exc_info=True)
         assert False, 'unexpected error' + str(ex)
示例#4
0
    def test_vectors(self):
        jf = 'test-vectors/appendix_a.json'

        try:
            testfile = open(jf, 'r')
        except:
            print('Error: cannot open ' + jf + '.')
            raise

        try:
            tv = ujson.load(testfile)
        except:
            print('Error: cannot load ' + jf + ' using ujson.load().')
            raise

        anyerr = False
        for row in tv:
            rhex = row.get('hex')
            if 'decoded' in row:
                decoded = row['decoded']

                if (type(decoded) is float):
                    status = _check_float(row, decoded)
                else:
                    status = _check(row, decoded)
                if (status):
                    anyerr = True
                continue
            elif 'diagnostic' in row:
                diag = row['diagnostic']
                checkf = _DIAGNOSTIC_TESTS.get(diag)
                if checkf is not None:
                    status = _check_foo(row, checkf)
                    if (status):
                        anyerr = True
                    continue

            # variously verbose log of what we're not testing:
            cbdata = ubinascii.a2b_base64(row['cbor'])
            try:
                pd = loads(cbdata)
            except:
                if rhex and (rhex in _EXPECT_EXCEPTION):
                    pass
                else:
                    print('Failed to load hex=' + str(rhex) + ' diag=' +
                          str(row.get('diagnostic') + '.'))
                pd = ''
            cd = None
            print('Skipping hex=' + str(rhex) + ' diag=' +
                  str(row.get('diagnostic')) + ' py=' + str(pd) + ' c=' +
                  str(cd) + '.')

        testfile.close()

        assert not anyerr
示例#5
0
def _check_foo(row, checkf):
    anyerr = False
    cbdata = ubinascii.a2b_base64(row['cbor'])
    cb = loads(cbdata)
    if not checkf(cb):
        anyerr = True
        print('Expected {0!r} got {1!r}. Failed to decode CBOR {2}.\n'.format(
            cb, checkf, ubinascii.hexlify(cbdata)))

    return anyerr
示例#6
0
def _check(row, decoded):
    anyerr = False
    cbdata = ubinascii.a2b_base64(row['cbor'])
    cb = loads(cbdata)
    if cb != decoded:
        anyerr = True
        print('Expected {0!r} got {1!r}. Failed to decode CBOR {2}.\n'.format(
            cb, decoded, ubinascii.hexlify(cbdata)))

    return anyerr
示例#7
0
 def _oso_bytearray(self, ob):
     ser = dumps(ob)
     try:
         o2 = loads(bytearray(ser))
         assert ob == o2, '%r != %r from %s' % (ob, o2,
                                                ubinascii.hexlify(ser))
     except Exception as e:
         print('failure on buf len={0} {1!r} ob={2!r} {3!r}; {4}\n'.format(
             len(ser), hexstr(ser), ob, ser, e))
         raise
示例#8
0
        def parse_raw_tx(self, tx_payload: str):
            self.logger.debug(f'parse raw tx: %s', tx_payload)
            try:
                b64_decode = base64.b64decode(tx_payload)
            except Exception as e:
                raise Exception('invalid base64 signedTx input.')

            tx = cbor.loads(b64_decode)
            tx_obj = utils.convert_raw_tx_to_obj(
                tx, {
                    'txTime': datetime.utcnow(),
                    'txOrdinal': None,
                    'status': TX_PENDING_STATUS,
                    'blockNum': None,
                    'blockHash': None,
                })
            return tx_obj
示例#9
0
def lora_callback(lora):
    #print('A LoRa event occured: ', end='')
    events = lora.events()
    if events & LoRa.RX_PACKET_EVENT:
        print('LoRa packet received')
        received = s.recv(64)
        received_object = cbor.loads(received)
        led_color_value = received_object.get('led-color', None)
        led_value = received_object.get('led', None)

        if led_color_value:
            pycom.rgbled(int(led_color_value))

        if led_value:
            if led_value == False:
                pycom.rgbled(0x000000)

    elif events & LoRa.TX_PACKET_EVENT:
        print('LoRa packet sent')
    def parse_block(blob: bytes, handle_regular_block: int):
        block_type, _ = cbor.loads(blob)
        header, body, attrib = _
        hashs = utils.header_to_id(header, block_type)
        common = {
          'hash': hashs,
          'magic': header[0],
          'prev_hash': header[1].hex(),
        }
        block_data = {}
        if block_type == 0:
            block_data.update(common)
            block_data.update(Block.handle_epoch_boundary_block(header))
        elif block_type == 1:
            block_data.update(common)
            block_data.update(Block.handle_regular_block(header, body, hashs, handle_regular_block))
        else:
            raise Exception(f'unexpected block type: {block_type}')

        return Block(**block_data)
示例#11
0
def deserliaize_CBOR(data: bytes) -> Any:
    return cbor.loads(data) if data else {}
示例#12
0
 def test_tuple(self):
     l = [1, 2, 3]
     t = tuple(l)
     ser = dumps(t)
     o2 = loads(ser)
     assert l == o2
示例#13
0
 def _osos(self, ob):
     obs = dumps(ob)
     o2 = loads(obs)
     o2s = dumps(o2)
     assert obs == o2s
示例#14
0
 def test_loads_none(self):
     try:
         loads(None)
         assert False, "expected ValueError when passing in None"
     except ValueError:
         pass