def _udp_thread(self):
        """
        UDP thread, reads data from the server and handles it.
        """

        while not self.udp_stop:
            try:
                data, src = self.sock.recvfrom(1024)
                #print(data.decode('latin-1'))
                _token = data[1:3]
                _type = data[3]
                if _type == PUSH_ACK:
                    self._log("Push ack")
                elif _type == PULL_ACK:
                    self._log("Pull ack")
                elif _type == PULL_RESP:
                    self.dwnb += 1
                    ack_error = TX_ERR_NONE
                    tx_pk = ujson.loads(data[4:])
                    if "tmst" in data:
                        tmst = tx_pk["txpk"]["tmst"]
                        t_us = tmst - utime.ticks_cpu() - 15000
                        if t_us < 0:
                            t_us += 0xFFFFFFFF
                        if t_us < 20000000:
                            self.uplink_alarm = Timer.Alarm(
                                handler=lambda x: self._send_down_link(
                                    ubinascii.a2b_base64(tx_pk["txpk"][
                                        "data"]), tx_pk["txpk"]["tmst"] - 50,
                                    tx_pk["txpk"]["datr"],
                                    int(tx_pk["txpk"]["freq"] * 1000) * 1000),
                                us=t_us)
                        else:
                            ack_error = TX_ERR_TOO_LATE
                            self._log('Downlink timestamp error!, t_us: {}',
                                      t_us)
                    else:
                        self.uplink_alarm = Timer.Alarm(
                            handler=lambda x: self._send_down_link_class_c(
                                ubinascii.a2b_base64(tx_pk["txpk"]["data"]),
                                tx_pk["txpk"]["datr"],
                                int(tx_pk["txpk"]["freq"] * 1000) * 1000),
                            us=50)
                    self._ack_pull_rsp(_token, ack_error)
                    self._log("Pull rsp")
            except usocket.timeout:
                pass
            except OSError as ex:
                if ex.errno != errno.EAGAIN:
                    self._log('UDP recv OSError Exception: {}', ex)
            except Exception as ex:
                self._log('UDP recv Exception: {}', ex)

            # wait before trying to receive again
            utime.sleep_ms(UDP_THREAD_CYCLE_MS)

        # we are to close the socket
        self.sock.close()
        self.udp_stop = False
        self._log('UDP thread stopped')
예제 #2
0
    def start(self, boot=True):
        if not self.sta_if.isconnected():
            print('Tentando conectar...', end="")
            self.sta_if.active(True)
            i = 0
            while i < len(self.config) and not self.sta_if.isconnected():
                self.connection(
                    ubinascii.a2b_base64(ubinascii.unhexlify(
                        self.config[i][0])),
                    ubinascii.a2b_base64(ubinascii.unhexlify(
                        self.config[i][1])))
                print(".", end="")
                time.sleep_ms(200)
                i += 1

        if not self.sta_if.isconnected() and boot:
            self.sta_if.active(False)
            print('Rede não conectada')
            d = dnsquery.start()
            self.connection(d[b's'].decode(), d[b'p'].decode())
            if self.sta_if.isconnected():
                self.config[self.lconf] = [
                    ubinascii.hexlify(ubinascii.b2a_base64(d[b's'])[:-1]),
                    ubinascii.hexlify(ubinascii.b2a_base64(d[b'p'])[:-1])
                ]
                f = open('config.json', 'w')
                f.write(ujson.dumps(self.config))
                f.close()
                machine.reset()
            else:
                time.sleep(1)
                machine.reset()

        return self.sta_if
예제 #3
0
 def __decrypt_img(self, json_payload):
     # decrypt key and IV using our RSA private key, then decrypt the image using AES
     dec_key = a2b_base64(
         rsa_decrypt(a2b_base64(json_payload['k']), self.private_key))
     dec_iv = a2b_base64(
         rsa_decrypt(a2b_base64(json_payload['i']), self.private_key))
     decryptor = aes(dec_key, 2, dec_iv)
     dec = decryptor.decrypt(a2b_base64(json_payload['d']))
     # server uses DEFLATE to keep sizes down
     return inflate(dec)
예제 #4
0
def admin(req, resp):
    if req.method == "POST":
        if b"Authorization" in req.headers:
            yield from start_response(resp)
            yield from resp.awrite(http_head)
            yield from resp.awrite('{}{}<br>{}'.format(div_cl_header,
                                                       href_adm_panel,
                                                       div_end))
            collect()  #Очищаем RAM
            yield from req.read_form_data()
            form = req.form
            if 'temp' and 'power' in list(form.keys()):
                setting_update(temph=form['temp'], pwr=form['power'])
            elif 'work_mode' and 'time_off' and 'time_on' in list(form.keys()):
                setting_update(timeon=form['time_on'],
                               timeoff=form['time_off'],
                               mod=form['work_mode'])
            elif 'ntp' and 'time' and 'daylight' and 'date' and 'tzone' in list(
                    form.keys()):
                update_config(tz=form['tzone'], dts=form['daylight'], rw='w')
                datetime_update(form['ntp'], form['date'], form['time'])
            elif 'wifi' and 'ssid' and 'pasw' in list(form.keys()):
                update_config(mode=form['wifi'],
                              ssid=form['ssid'],
                              pssw=form['pasw'],
                              rw='w')
            elif 'login' and 'repassw' and 'passw' in list(form.keys()):
                setroot(form['login'], form['passw'])
            yield from resp.awrite('{}{}{}'.format(div_cl_info, 'Setting OK!',
                                                   div_end))
    else:
        if b"Authorization" not in req.headers:
            yield from resp.awrite(
                'HTTP/1.0 401 NA\r\n'
                'WWW-Authenticate: Basic realm="Picoweb Realm"\r\n'
                '\r\n')
            return
        auth = req.headers[b"Authorization"].split(None, 1)[1]
        auth = a2b_base64(auth).decode()
        username, passwd = auth.split(":", 1)
        if setpasswd(username.lower(), passwd) == read_write_root():
            yield from start_response(resp)
            yield from resp.awrite(http_head)
            yield from resp.awrite('{}{}<br>{}'.format(div_cl_header,
                                                       href_adm_panel,
                                                       div_end))
            yield from resp.awrite(div_cl_admin)
            yield from resp.awrite('{}<br>'.format(temp_power))
            yield from resp.awrite('{}<br>'.format(mode_time))
            yield from resp.awrite('{}<br>'.format(date_set))
            yield from resp.awrite('{}<br>'.format(wifi_form))
            yield from resp.awrite('{}<br>'.format(passw_form))
            yield from resp.awrite(div_end)
        else:
            yield from start_response(resp)
            yield from resp.awrite(http_head)
            yield from resp.awrite('{}{}{}'.format(div_cl_header,
                                                   span_err_pasw, div_end))
    yield from resp.awrite(http_footer)
    collect()  # Очищаем RAM
예제 #5
0
    def on_receive_mqtt(self, topic, message):
        if topic != "mcer4294967296/data":
            return
        # stuff over mqtt will be encrypted
        try:
            encrypted = ubinascii.a2b_base64(message)
            decrypted = self.cipher.decrypt(encrypted)
        except:
            return

        if decrypted.startswith("YOLO::override"):
            order = decrypted.split("::")[2]
            if order == "lock":
                self.lock()
            elif order == "unlock":
                self.unlock()
            self.override = True
        elif decrypted.startswith("YOLO::unoverride"):
            self.override = False
        elif decrypted.startswith("YOLO::dist"):
            dist = decrypted.split("::")[2]
            if dist > self.dist_thresh:
                # if owner is pretty far away, we increase the poll interval
                # because it won't result in anything anyways.
                self.lock()
                self.poll_interval = 30
            else:
                # if owner is coming back home, we don't unlock the door because
                # maybe he wants to take a cigarette somewhere first.
                # but we decrease the interval so that we can detect more quickly.
                self.poll_interval = 5
        else:
            return
예제 #6
0
def serve():
    bme = bme280.BME280(i2c=i2c)
    # create the onewire object
    ds = ds18x20.DS18X20(onewire.OneWire(Pin(2)))  # the ds18b20 is on GPIO4
    # mqtt client
    client_id = CONFIG['MQTT_CLIENT_ID_PREFIX'] + ubinascii.hexlify(
        machine.unique_id()).decode('utf-8')
    password = ubinascii.a2b_base64(CONFIG['MQTT_PASSWORD'])
    client = MQTTClient(client_id,
                        CONFIG['MQTT_BROKER'],
                        user=CONFIG['MQTT_USER'],
                        password=password,
                        port=CONFIG['MQTT_PORT'])
    client.connect()
    print("'%s' is connected to '%s'" % (client_id, CONFIG['MQTT_BROKER']))

    while True:
        temp = bme.temperature
        hum = bme.humidity
        pres = bme.pressure

        temps = ds18b20.read_temperatures(ds)

        # publish the values
        client.publish("%s.temp_c" % client_id, temp)
        client.publish("%s.humidity_rh" % client_id, hum)
        client.publish("%s.pressure_hpa" % client_id, pres)
        for serial_nbr, temp in temps.items():
            client.publish("%s.%s.temp_c" % (client_id, serial_nbr),
                           '%0.5f' % temp)

        sleep(300)
예제 #7
0
파일: upl.py 프로젝트: zindy/uPyLoader
def upload(file_name):
    suc = False
    with open(file_name, "wb") as f:
        while True:
            d = _read_timeout(3)
            if not d or d[0] != "#":
                sys.stdout.write("#2")
                break
            cnt = int(d[1:3])
            if cnt == 0:
                suc = True
                break
            d = _read_timeout(cnt)
            if d:
                try:
                    f.write(a2b_base64(d))
                except OSError as e:
                    sys.stdout.write("#5")
                    sys.print_exception(e)
                    break
                else:
                    sys.stdout.write("#1")
            else:
                sys.stdout.write("#3")
                break
    sys.stdout.write("#0" if suc else "#4")
예제 #8
0
 async def handle_input(self, data, peer):
     cmd = data.decode('utf-8').strip('\n')
     if  self.connections[peer]['upload']:
         if cmd == 'done':
             print('Done upload.')
             self.connections[peer]['upload'] = False
             self.connections[peer]['upload_file'].close()
             self.connections[peer]['upload_file'] = ''
         elif self.connections[peer]['upload_file'] == '':
             filename = cmd
             print('Filename: {}'.format(filename))
             if not (filename == 'boot.py' or filename == 'main.py'):
                 print('Opened {}'.format(filename))
                 self.connections[peer]['upload_file'] = open(filename,'w+')
                 await self.connections[peer]['writer'].awrite('Ok. Begin upload.\n')
         else:
             print('Wrote data.')
             self.connections[peer]['upload_file'].write(a2b_base64(data).decode('utf-8'))
     elif cmd in self.funcs:
         await self.funcs[cmd](peer)
     elif cmd.lower().startswith('simon says'):
         await self.connections[peer]['writer'].awrite('Simon didn\'t say that.\n')
         await self.connections[peer]['writer'].drain()
     elif cmd.lower().startswith('update_led'):
         self.duty_led = int(cmd.split(' ')[1].strip('\n'))
     else:
         await self.connections[peer]['writer'].awrite('Simon says ' + cmd + '\n')
         await self.connections[peer]['writer'].drain()
예제 #9
0
파일: main.py 프로젝트: Brent-rb/University
def handle_command_send(js):
    if type(js) is not dict:
        return None
    data = js['data']
    b = binascii.a2b_base64(data)
    lora.send(b)
    return None
예제 #10
0
    def _decodeBase64(self, data):
        s = data
        if isinstance(s, str):
            s = bytes(data, "utf-8")

        msg = s.replace(b"-", b"+").replace(b"_", b"/")
        return ubinascii.a2b_base64(msg)
예제 #11
0
 def load_users(self):
     files = os.listdir()
     if not self.users_conf_name in files:
         with open(self.users_conf_name, "w") as f:
             info = {"users": [], "features": []}
             f.write(json.dumps(info))
             return [], []
     with open(self.users_conf_name) as f:
         conf = f.read()
         users = []
         try:
             conf = json.loads(conf)
             features = []
             for i, fea in enumerate(conf['features']):
                 fea = ubinascii.a2b_base64(fea)
                 if fea:  #TODO: length
                     users.append(conf['users'][i])
                     features.append(fea)
                     print("decoded feature:", fea)
                 else:
                     print("user {}'s feature not valid".format(
                         conf['users'][i]))
         except Exception:
             print("parse config file error")
             return [], []
         return users, features
예제 #12
0
def parse_transaction(b64_tx, success_callback=None, error_callback=None):
    # we will go to main afterwards
    show_main()
    try:
        raw = a2b_base64(b64_tx)
        tx = psbt.PSBT.parse(raw)
    except:
        gui.error("Failed at transaction parsing")
        if error_callback is not None:
            error_callback("invalid argument")
        return
    # blue wallet trick - if the fingerprint is 0 we use our fingerprint
    for scope in [tx.inputs, tx.outputs]:
        for el in scope:
            for der in el.bip32_derivations:
                if el.bip32_derivations[
                        der].fingerprint == b'\x00\x00\x00\x00':
                    el.bip32_derivations[
                        der].fingerprint = keystore.fingerprint
    try:
        data = keystore.check_psbt(tx)
    except Exception as e:
        gui.error("Problem with the transaction: %r" % e)
        if error_callback is not None:
            error_callback("invalid argument")
        return
    title = "Spending %u\nfrom %s" % (data["spending"], data["wallet"].name)
    popups.prompt_tx(title,
                     data,
                     ok=cb_with_args(sign_psbt,
                                     wallet=data["wallet"],
                                     tx=tx,
                                     success_callback=success_callback),
                     cancel=cb_with_args(error_callback, "user cancel"))
예제 #13
0
def plays(files, display, sx=0, sy=0, qt=0):
    f = open(files, "rb")
    inf = f.readline()
    info = inf.decode()
    try:
        x, y, times, fps = json.loads(info)
    except Exception as e:
        print("Wrong File")
        return False
    ce = time.ticks_ms()
    for i in range(times * fps):
        t = time.ticks_ms()
        c = f.readline()
        q = ubinascii.a2b_base64(c)
        showN(q, display, x, y, sx, sy)
        if i % 10:
            time.sleep_ms(round(1000 / fps) - time.ticks_ms() + t)
        else:
            time.sleep_ms(round(1000 / fps) - time.ticks_ms() + t - qt)
    rec = time.ticks_ms() - ce
    print(rec)
    rex = (times * 1000 - rec) * 10 / (fps * times)
    print("QT:", rex)
    display.fill(0)
    display.show()
    return 'fin'
예제 #14
0
def GenerateAzureSasToken(uri, key, expiryTimestamp, policy_name=None):
    from ubinascii import a2b_base64, b2a_base64

    def _quote(s):
        r = ''
        for c in str(s):
            if (c >= 'a' and c <= 'z') or \
               (c >= '0' and c <= '9') or \
               (c >= 'A' and c <= 'Z') or \
               (c in '.-_') :
                r += c
            else:
                r += '%%%02X' % ord(c)
        return r

    uri = _quote(uri)
    sign_key = b'%s\n%d' % (uri, int(expiryTimestamp))
    key = a2b_base64(key)
    hmac = HMACSha256(key, sign_key)
    signature = _quote(b2a_base64(hmac).decode().strip())
    token = 'sr=' + uri + '&' + 'sig=' + signature + '&' + 'se=' + str(
        expiryTimestamp)
    if policy_name:
        token += '&' + 'skn=' + policy_name
    return 'SharedAccessSignature ' + token
예제 #15
0
def serve():
    bme = bme280.BME280(i2c=i2c)
    client_id = CONFIG['MQTT_CLIENT_ID_PREFIX'] + ubinascii.hexlify(
        machine.unique_id()).decode('utf-8')
    password = ubinascii.a2b_base64(CONFIG['MQTT_PASSWORD'])
    client = MQTTClient(client_id,
                        CONFIG['MQTT_BROKER'],
                        user=CONFIG['MQTT_USER'],
                        password=password,
                        port=CONFIG['MQTT_PORT'])
    client.connect()
    print("'%s' is connected to '%s'" % (client_id, CONFIG['MQTT_BROKER']))

    while True:
        temp = bme.temperature
        hum = bme.humidity
        pres = bme.pressure
        # uncomment for temperature in Fahrenheit
        #temp = (bme.read_temperature()/100) * (9/5) + 32
        #temp = str(round(temp, 2)) + 'F'

        # publish the values
        client.publish("%s.temperature_c" % client_id, temp)
        client.publish("%s.humidity_rh" % client_id, hum)
        client.publish("%s.pressure_hpa" % client_id, pres)

        sleep(300)
예제 #16
0
 def auth(req, resp):
     auth = req.headers.get(b"Authorization")
     if not auth:
         log.warning('no auth found')
         yield from resp.awrite(
             'HTTP/1.0 401 NA\r\n'
             'WWW-Authenticate: Basic realm="SyncSign Web Realm"\r\n'
             '\r\n')
         return
     auth = auth.split(None, 1)[1]
     auth = ubinascii.a2b_base64(auth).decode()
     req.username, req.passwd = auth.split(":", 1)
     # verify credential
     try:
         if req.username == DEFAULT_USERNAME and req.passwd == DEFAULT_PASSWD:
             yield from func(req, resp)
         else:
             log.warning('not match')
             raise ValueError(
                 'Invalid configuration, or unauthorized access is prohibited.'
             )
     except Exception as e:  # if first run
         log.exception(e, 'error occured.')
         yield from picoweb.start_response(
             resp, content_type="text/html", status="401",
             headers=None)  # 403 cannot continue with a bad password input
         yield from resp.awrite("Unauthorized access is prohibited.")
예제 #17
0
def mqtt_boot_subscribe(topic, msg):
    print(str(topic))
    print(msg)
    global waitConfig
    try:
        msgDict = ujson.loads(msg)
        print(msgDict)
        # print(initconfig)
        # if str(topic)==initconfig["board"]["id"]:
        print("searching for action")
        if msgDict["msg"]["action"] == "bootstrap":
            print("Bootstrap")
            config = ujson.loads(ubinascii.a2b_base64(msgDict["msg"]["value"]))
            print(config)
            save_init_file(config)
            update_boot_wifi()
            # load_init_file()
            waitConfig = False
        if msgDict["msg"]["action"] == "id":
            print("ID")
            initconfig["board"]["name"] = msgDict["msg"]["value"]

    except BaseException as e:
        print("An exception occurred during boot")
        import sys
        sys.print_exception(e)
        sleep(30)
        machine.reset()
예제 #18
0
 def decode_value(cls, prevout, text):
     # base64 decode, xor w/ hash, decode as uint64
     xor = pack('<Q', prevout.hash & ((1 << 64) - 1))
     val = a2b_base64(text + '=')
     assert len(val) == 8
     val = bytes(i ^ j for i, j in zip(xor, val))
     return unpack('<Q', val)[0]
예제 #19
0
 def write(self, payload):
     if not isinstance(payload, bytes):
         payload = payload.encode('UTF-8')
     payload = binascii.a2b_base64(payload)
     self.hasher.update(payload)
     self.fd.write(payload)
     self.bwrite += len(payload)
     return self.bwrite
예제 #20
0
def decode(input, output):
    """Decode a file; input and output are binary files."""
    while True:
        line = input.readline()
        if not line:
            break
        s = binascii.a2b_base64(line)
        output.write(s)
예제 #21
0
def decode(input, output):
    """Decode a file; input and output are binary files."""
    while True:
        line = input.readline()
        if not line:
            break
        s = binascii.a2b_base64(line)
        output.write(s)
def b64decode(s, altchars=None, validate=False):
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise ubinascii.Error('Non-base64 digit found')
    return ubinascii.a2b_base64(s)
예제 #23
0
    def fromString(strData):

        rawText = ubinascii.a2b_base64(strData)
        tuple = json.loads(rawText)
        content, target, sender, sendCount, isACK, hasBeenAcced, isSelfInformation = tuple
        message = Message(content, target, sender, sendCount, isACK,
                          hasBeenAcced, isSelfInformation)

        return message
예제 #24
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
예제 #25
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
예제 #26
0
파일: users.py 프로젝트: ramsemune/firmware
def calc_local_pincode(psbt_sha, hmac_secret):
    # Given a b64 encoded secret (shared from CC over USB) and the PSBT
    # being authorized, cook up 6 digits for local PIN code
    from ubinascii import a2b_base64
    key = a2b_base64(hmac_secret)
    assert len(psbt_sha) == 32
    digest = hmac_sha256(key, psbt_sha)

    num = ustruct.unpack('>I', digest[-4:])[0] & 0x7fffffff
    return '%06d' % (num % 1000000)
예제 #27
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
    def fromString(strData):

        rawText = ubinascii.a2b_base64(strData)
        tuple = json.loads(rawText)

        name, mac, mlEID, firmware, clientsConnectedAtMySite = tuple

        decoration = NetworkNodeDecoration(name, mac, mlEID, firmware,
                                           clientsConnectedAtMySite)

        return decoration
예제 #29
0
    def _compute_key(self, key, payload):
        try:
            secret = ubinascii.a2b_base64(key)
        except:
            self._logger.info("ERROR: broken base64 secret => `" + key + "`")
            sys.exit()

        ret = ubinascii.b2a_base64(hmac(secret, msg=payload.encode(
            'utf8'), digestmod=hashlib.sha256).digest()).decode('utf-8')
        ret = ret[:-1]
        return ret
예제 #30
0
def sub_cb(topic, msg):
    print((topic, msg))
    print((msg))
    j = msg
    m = j.decode()
    o = json.loads(m)
    t = (o['payload_raw'])
    print(t)
    ts = (str(ubinascii.a2b_base64(t).decode()))

    print(ts)
    lcd_scrol.mess(ts)
예제 #31
0
def parse_transaction(b64_tx, success_callback=None, error_callback=None):
    # we will go to main afterwards
    show_main()
    try:
        raw = a2b_base64(b64_tx)
        tx = psbt.PSBT.parse(raw)
    except:
        gui.error("Failed at transaction parsing")
        if error_callback is not None:
            error_callback("invalid argument")
        return
    # blue wallet trick - if the fingerprint is 0 we use our fingerprint
    for scope in [tx.inputs, tx.outputs]:
        for el in scope:
            for der in el.bip32_derivations:
                if el.bip32_derivations[der].fingerprint == b'\x00\x00\x00\x00':
                    el.bip32_derivations[der].fingerprint = keystore.fingerprint
    try:
        data = keystore.check_psbt(tx)
    except Exception as e:
        gui.error("Problem with the transaction: %r" % e)
        if error_callback is not None:
            error_callback("invalid argument")
        return

    # check for address gap limit
    gap_limit = False
    w = data["wallet"]
    wallet_key = b"\xfc\xca\x01" + data["wallet"].fingerprint
    for el in tx.inputs + tx.outputs:
        if el.bip32_derivations:
            # full PSBT
            for der in el.bip32_derivations:
                drv = el.bip32_derivations[der].derivation
                if drv[-1] > w.gap_limit + (w.last_chg_idx if drv[-2] else w.last_rcv_idx):
                    gap_limit = True
        elif wallet_key in el.unknown:
            # compressed PSBT
            idxs = el.unknown[wallet_key]
            chg = int.from_bytes(idxs[0:4], 'little')
            idx = int.from_bytes(idxs[4:8], 'little')
            if idx > w.gap_limit + (w.last_chg_idx if chg else w.last_rcv_idx):
                gap_limit = True
    if gap_limit:
        data["warning"] = ("#ff0000 Possible gap limit exceeded with some#\n"
                           "#ff0000 addresses. Your funds may get locked. #\n "
                           "#ff0000 Proceed at your own risk!#")

    title = "Spending %u\nfrom %s" % (data["spending"], data["wallet"].name)
    popups.prompt_tx(title, data,
        ok=cb_with_args(sign_psbt, wallet=data["wallet"], tx=tx, success_callback=success_callback),
        cancel=cb_with_args(error_callback, "user cancel")
    )
예제 #32
0
    def _udp_thread(self):
        """
        UDP thread, reads data from the server and handles it.
        """

        while not self.udp_stop:
            try:
                data, src = self.sock.recvfrom(1024)
                _token = data[1:3]
                _type = data[3]
                if _type == PUSH_ACK:
                    self._log("Push ack")
                elif _type == PULL_ACK:
                    self._log("Pull ack")
                elif _type == PULL_RESP:
                    self.dwnb += 1
                    ack_error = TX_ERR_NONE
                    tx_pk = ujson.loads(data[4:])
                    tmst = tx_pk["txpk"]["tmst"]
                    t_us = tmst - utime.ticks_us() - 12500
                    if t_us < 0:
                        t_us += 0xFFFFFFFF
                    if t_us < 20000000:
                        self.uplink_alarm = Timer.Alarm(
                            handler=lambda x: self._send_down_link(
                                ubinascii.a2b_base64(tx_pk["txpk"]["data"]),
                                tx_pk["txpk"]["tmst"] - 50, tx_pk["txpk"]["datr"],
                                int(tx_pk["txpk"]["freq"] * 1000000)
                            ), 
                            us=t_us
                        )
                    else:
                        ack_error = TX_ERR_TOO_LATE
                        self._log('Downlink timestamp error!, t_us: {}', t_us)
                    self._ack_pull_rsp(_token, ack_error)
                    self._log("Pull rsp")
            except usocket.timeout:
                pass
            except OSError as ex:
                if ex.errno != errno.EAGAIN:
                    self._log('UDP recv OSError Exception: {}', ex)
            except Exception as ex:
                self._log('UDP recv Exception: {}', ex)

            # wait before trying to receive again
            utime.sleep_ms(UDP_THREAD_CYCLE_MS)

        # we are to close the socket
        self.sock.close()
        self.udp_stop = False
        self._log('UDP thread stopped')
예제 #33
0
    def auth(req, resp):
        auth = req.headers.get(b"Authorization")
        if not auth:
            yield from resp.awrite(
                'HTTP/1.0 401 NA\r\n'
                'WWW-Authenticate: Basic realm="Picoweb Realm"\r\n'
                '\r\n'
            )
            return

        auth = auth.split(None, 1)[1]
        auth = ubinascii.a2b_base64(auth).decode()
        req.username, req.passwd = auth.split(":", 1)
        yield from func(req, resp)
예제 #34
0
def index(req, resp):
    if b"Authorization" not in req.headers:
        yield from resp.awrite(
            'HTTP/1.0 401 NA\r\n'
            'WWW-Authenticate: Basic realm="Picoweb Realm"\r\n'
            '\r\n'
        )
        return

    auth = req.headers[b"Authorization"].split(None, 1)[1]
    auth = ubinascii.a2b_base64(auth).decode()
    username, passwd = auth.split(":", 1)
    yield from picoweb.start_response(resp)
    yield from resp.awrite("You logged in with username: %s, password: %s" % (username, passwd))
예제 #35
0
 def is_authorized(self, authorization):
     import ubinascii
     try:
         tmp = authorization.split()
         if tmp[0].lower() == "basic":
             str = ubinascii.a2b_base64(tmp[1].strip().encode()).decode()
             ra = str.split(':')
             auth_result = ra[0] == self._config['user'] and ra[1] == self._config['password']
             return auth_result, ra[0]
         else:
             raise BadRequestException(
                 "Unsupported authorization method: {}".format(tmp[0]))
     except Exception as e:
         raise BadRequestException(e)
예제 #36
0
def b64decode(s, altchars=None, validate=False):
    """Decode a Base64 encoded byte string.

    s is the byte string to decode.  Optional altchars must be a
    string of length 2 which specifies the alternative alphabet used
    instead of the '+' and '/' characters.

    The decoded string is returned.  A binascii.Error is raised if s is
    incorrectly padded.

    If validate is False (the default), non-base64-alphabet characters are
    discarded prior to the padding check.  If validate is True,
    non-base64-alphabet characters in the input result in a binascii.Error.
    """
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s)
예제 #37
0
 def getValue(self):
     # BASE64 decode the data !!!!
     converted = a2b_base64(self.data['binaryMeterValue'])
     return converted
예제 #38
0
def decodebytes(s):
    """Decode a bytestring of base-64 data into a bytestring."""
    if not isinstance(s, bytes_types):
        raise TypeError("expected bytes, not %s" % s.__class__.__name__)
    return binascii.a2b_base64(s)
예제 #39
0
try:
    import ubinascii as binascii
except ImportError:
    import binascii

print(binascii.a2b_base64(b""))
print(binascii.a2b_base64(b"Zg=="))
print(binascii.a2b_base64(b"Zm8="))
print(binascii.a2b_base64(b"Zm9v"))
print(binascii.a2b_base64(b"Zm9vYg=="))
print(binascii.a2b_base64(b"Zm9vYmE="))
print(binascii.a2b_base64(b"Zm9vYmFy"))

print(binascii.a2b_base64(b"AAECAwQFBgc="))
print(binascii.a2b_base64(b"CAkKCwwNDg8="))
print(binascii.a2b_base64(b"f4D/"))
print(binascii.a2b_base64(b"f4D+"))  # convert '+'
print(binascii.a2b_base64(b"MTIzNEFCQ0RhYmNk"))

try:
    print(binascii.a2b_base64(b"abc"))
except ValueError:
    print("ValueError")
try:
    print(binascii.a2b_base64(b"abcde="))
except ValueError:
    print("ValueError")
try:
    print(binascii.a2b_base64(b"ab*d"))
except ValueError:
    print("ValueError")
예제 #40
0
rtc.ntp_sync('fr.pool.ntp.org')

bt = Bluetooth()
try:
    bt.start_scan(-1)
except:
    bt.stop_scan()
    bt.start_scan(-1)

while True:
    try:
        adv = bt.get_adv()
        if adv:
            data = str(adv.data, "utf-8")
            data = str(data.split("#")[1][:8], "utf-8")
            data = ubinascii.a2b_base64(data)
            temperature = extractTemperature(data)
            humidity = extractHumidity(data)
            pressure = extractPressure(data)
            id = str(ubinascii.hexlify(adv.mac), "utf-8")

            content = '{"temperature": %s, "humidity": %s, "pressure" : %s, "mac": %s, "timestamp": "%s"}' % (
                temperature, humidity, pressure, id, rtc.now())
            print(content)
            sendData.send(host='http://192.168.1.15', port=1338, data=content)
            pycom.rgbled(0x007f00)  # green
            time.sleep(0.1)
            pycom.rgbled(0)
            try:
                bt.stop_scan()
            except:
예제 #41
0
try:
    try:
        import ubinascii as binascii
    except ImportError:
        import binascii
except ImportError:
    print("SKIP")
    raise SystemExit

print(binascii.a2b_base64(b''))
print(binascii.a2b_base64(b'Zg=='))
print(binascii.a2b_base64(b'Zm8='))
print(binascii.a2b_base64(b'Zm9v'))
print(binascii.a2b_base64(b'Zm9vYg=='))
print(binascii.a2b_base64(b'Zm9vYmE='))
print(binascii.a2b_base64(b'Zm9vYmFy'))

print(binascii.a2b_base64(b'AAECAwQFBgc='))
print(binascii.a2b_base64(b'CAkKCwwNDg8='))
print(binascii.a2b_base64(b'f4D/'))
print(binascii.a2b_base64(b'f4D+')) # convert '+'
print(binascii.a2b_base64(b'MTIzNEFCQ0RhYmNk'))

# Ignore invalid characters and pad sequences
print(binascii.a2b_base64(b'Zm9v\n'))
print(binascii.a2b_base64(b'Zm\x009v\n'))
print(binascii.a2b_base64(b'Zm9v=='))
print(binascii.a2b_base64(b'Zm9v==='))
print(binascii.a2b_base64(b'Zm9v===YmFy'))

try: