Example #1
0
def verify_txi(tx, txi, idx, testnet=False):
    prev_tx = fetch(txi["txid"], testnet)
    lock_script = prev_tx["txos"][txi["idx"]]["script"]
    # check if p2sh-p2wpkh or p2sh-p2wsh, p2sh_pattern = [OP_HASH160(0xa9) <hash:20bytes> OP_EQUAL(0x87)]
    if len(lock_script) == 3 and lock_script[0] == 0xa9 and \
            type(lock_script[1]) == bytes and len(lock_script[1]) == 20 and lock_script[2] == 0x87:
        # the last cmd has to be the redeem_script
        raw_redeem_script = txi["script"][-1]
        # encode_varint로 변환해야 하는것 아닌가? 원소사이즈는 max 520bytes
        # 확인해보니 (지미송)코드에 문제 발견
        # script.parse에서도 length = util.read_varint(s)로 읽고 있음.
        # 그래서 encode_varint로 변경
        # 인코딩: https://github.com/jimmysong/programmingbitcoin/blob/2a6558263923214320bbdeb10826464fe24ef540/code-ch13/tx.py#L313
        # 디코딩: https://github.com/jimmysong/programmingbitcoin/blob/2a6558263923214320bbdeb10826464fe24ef540/code-ch13/script.py#L78
        # raw_redeem_script = util.int_to_little_endian(len(raw_redeem_script), 1) + raw_redeem_script
        raw_redeem_script = util.encode_varint(
            len(raw_redeem_script)) + raw_redeem_script
        _, redeem_script = script.parse(
            BytesIO(raw_redeem_script))  # (length, script)
        if script.is_p2wpkh(redeem_script):
            z = sig_hash_bip143(prev_tx,
                                tx,
                                txi,
                                redeem_script=redeem_script,
                                witness_script=None,
                                testnet=testnet)
            witness = txi["wits"]
        elif script.is_p2wsh(redeem_script):
            raw_witness_script = txi["wits"][-1]  # wits:[,,,witness_script]
            raw_witness_script = util.encode_varint(
                len(raw_witness_script)) + raw_witness_script
            _, witness_script = script.parse(BytesIO(raw_witness_script))
            z = sig_hash_bip143(prev_tx,
                                tx,
                                txi,
                                witness_script=witness_script)
            witness = txi["wits"]
        else:
            z = sig_hash(tx, idx, redeem_script)
            witness = None
    else:  # p2wpkh or p2wsh or ...
        if script.is_p2wpkh(lock_script):
            z = sig_hash_bip143(prev_tx, tx, txi)
            witness = txi["wits"]
        elif script.is_p2wsh(lock_script):
            raw_witness_script = txi["wits"][-1]
            raw_witness_script = util.encode_varint(
                len(raw_witness_script)) + raw_witness_script
            _, witness_script = script.parse(BytesIO(raw_witness_script))
            z = sig_hash_bip143(prev_tx,
                                tx,
                                txi,
                                witness_script=witness_script)
            witness = txi["wits"]
        else:
            z = sig_hash(tx, idx, lock_script)
            witness = None
    commands = txi["script"] + lock_script
    return script.evaluate(commands, z, witness)
Example #2
0
async def periodic():
    sleep_min = 1
    while True:
        try:
            script.parse()
            print(f"Going to sleep for {sleep_min} minute(s)")
        except Exception as err:
            print(err)
            print(
                f"!!! Something went wrong !!! Retrying in {sleep_min} minute(s)"
            )
        await asyncio.sleep(sleep_min * 60)
Example #3
0
def parse_txo(s):
    txo = {
        "amount": 0,
        "script.len": 0,
        "script": ""
    }
    # amount is an integer in 8 bytes, little endian (amount = satoshi * 10**8, 1 satoshi = 0.00000001btc)
    txo["amount"] = util.little_endian_to_int(s.read(8))
    txo["script.len"], txo["script"] = script.parse(s)  # lock script
    return txo
Example #4
0
File: cyc.py Project: boisgera/cyc
def main(args=None):
    args = args or sys.argv[1:]
    spec = "help main" 
    options, filenames = script.parse(spec, args)
    if options.help or not filenames:
        print help()
    else:
        main = bool(options.main)
        with temp_dir() as build_dir:
            for filename in filenames:
                compile(filename, main=main, build_dir=build_dir)
Example #5
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]
    options, args = script.parse("help input= output= debug", args)
    if options.help:
        print help()
        sys.exit(0)
    elif not args or len(args) > 1:
        print help()
        sys.exit(1)
    else:
        module_name = args[0]

    module = importlib.import_module(module_name)
    filename = script.first(options.input) or inspect.getsourcefile(module)
    if filename is None:
        raise RuntimeError("missing input filename")
    source = open(filename).read()

    debug = bool(options.debug)

    markdown = docgen(module, source, debug)
    if not options.output:
        print markdown
    else:
        output = script.first(options.output)
        basename = os.path.basename(output)
        if len(basename.split(".")) >= 2:
            ext = basename.split(".")[-1]
        else:
            ext = None
        if ext == "tex":
            sh.pandoc(read="markdown", toc=True, standalone=True, write="latex", o=output, _in=markdown)
        elif ext == "pdf":
            try: # keep that somewhere, but use pandoc to generate the pdf ?
                latex = ".".join(basename.split(".")[:-1]) + ".tex"
                build = tempfile.mkdtemp()
                cwd = os.getcwd()
                os.chdir(build)
                sh.pandoc(read="markdown", toc=True, standalone=True, write="latex", o=latex, _in=markdown)
                sh.xelatex(latex)
                sh.xelatex(latex)
                os.chdir(cwd)
                sh.cp(os.path.join(build, latex[:-4] + ".pdf"), output)
            finally:
                try:
                    shutil.rmtree(build) # delete directory
                except OSError, e:
                    if e.errno != 2: # code 2 - no such file or directory
                        raise
        else:
Example #6
0
def parse_txi(s):
    txi = {
        "txid": 0,  # 32bytes, not hex value.
        "idx": 0,
        "script.len": 0,
        "script": [],
        "seq.no": 0,
        "wits": []
    }
    txi["txid"] = s.read(32)[::-1]  # prev_tx is 32 bytes, little endian // le to be
    txi["idx"] = util.little_endian_to_int(s.read(4))  # prev_index is an integer in 4 bytes, little endian
    txi["script.len"], txi["script"] = script.parse(s)  # parse script
    txi["seq.no"] = util.little_endian_to_int(s.read(4))  # sequence is an integer in 4 bytes, little-endian
    # wits: witness script
    return txi
Example #7
0
                dic_exp_conf["EPISODE_LEN"] /
                dic_traffic_env_conf["MIN_ACTION_TIME"]):
            action_list = []
            for one_state in state:
                s = convert_to_input(one_state, dic_traffic_env_conf)
                action = actor.choose_action(
                    s)  # one for multi-state, the other for multi-intersection
                action_list.append(action)  # for multi-state

            next_state, reward, done, _ = env.step(action_list)

            s = convert_to_input(state[0], dic_traffic_env_conf)
            s_ = convert_to_input(next_state[0], dic_traffic_env_conf)

            td_error = critic.learn(s, reward[0], s_)
            act_one_hot = np.zeros((1, 8))
            act_one_hot[0, action] = 1.0
            actor.learn(s, act_one_hot, td_error)

            state = next_state
            step_num += 1
            stop_cnt += 1
        env.bulk_log(i)
        write_summary(dic_path, dic_exp_conf, i)


if __name__ == '__main__':
    args = parse()
    os.environ["CUDA_VISIBLE_DEVICES"] = args.visible_gpu
    main(args)