def main():
    parser = OptionParser(
        usage='usage: %prog [options] wallet_file_name password',
        description='Create a wallet with the given wallet name and password.')
    add_base_options(parser)
    (options, args) = parser.parse_args()
    if options.wallet_password_stdin:
        stdin = sys.stdin.read()
        password = stdin.encode("utf-8")
    else:
        assert len(
            args
        ) > 1, "must provide password via stdin (see --help), or as second argument."
        password = args[1].encode("utf-8")
    load_program_config(config_path=options.datadir)
    wallet_root_path = os.path.join(jm_single().datadir, "wallets")
    wallet_name = os.path.join(wallet_root_path, args[0])
    if jm_single().config.get("POLICY", "native") == "true":
        walletclass = SegwitWallet
    else:
        walletclass = SegwitLegacyWallet
    wallet = create_wallet(wallet_name, password, 4, walletclass)
    jmprint("recovery_seed:{}".format(wallet.get_mnemonic_words()[0]),
            "important")
    wallet.close()
示例#2
0
def main():
    parser = argparse.ArgumentParser(
        description="Convert old joinmarket json wallet format to new jmdat "
                    "format")
    parser.add_argument('old_wallet_file', type=open)
    parser.add_argument('--name', '-n', required=False, dest='name',
                        help="Name of the new wallet file. Default: [old wallet name].jmdat")
    # hack; not using jmclient.add_base_options because ArgumentParser not OptionParser:
    parser.add_argument(
        '--datadir',
        dest='datadir',
        default="",
        help='Specify the path to a directory you want to use to store your user'
        'data - wallets, logs and commitment files - and your joinmarket.cfg. '
        'By default, the directory .' + JM_APP_NAME + ' is used.'
    )

    try:
        args = parser.parse_args()
    except Exception as e:
        print("Error: {}".format(e))
        return
    load_program_config(config_path=args.datadir)
    data = parse_old_wallet(args.old_wallet_file)

    if not data:
        return

    file_name = args.name or\
        os.path.split(args.old_wallet_file.name)[-1].rsplit('.', 1)[0] + '.jmdat'
    wallet_path = get_wallet_path(file_name, None)
    if new_wallet_from_data(data, wallet_path):
        print("New wallet file created at {}".format(wallet_path))
    else:
        print("Failed to convert wallet.")
示例#3
0
 def setUp(self):
     global clientfactory
     print("setUp()")
     params = [[False, False], [True, False], [False, True], [-1, False]]
     load_program_config()
     jm_single().maker_timeout_sec = 1
     self.port = reactor.listenTCP(28184, JMTestServerProtocolFactory())
     self.addCleanup(self.port.stopListening)
     def cb(client):
         self.client = client
         self.addCleanup(self.client.transport.loseConnection)
     clientfactories = []
     takers = [DummyTaker(
         None, ["a", "b"], callbacks=(
             None, None, dummy_taker_finished)) for _ in range(len(params))]
     for i, p in enumerate(params):
         takers[i].set_fail_init(p[0])
         takers[i].set_fail_utxos(p[1])
         takers[i].testflag = True
         if i != 0:
             clientfactories.append(JMClientProtocolFactory(takers[i]))
             clientconn = reactor.connectTCP("localhost", 28184,
                                             clientfactories[i])
             self.addCleanup(clientconn.disconnect)
         else:
             clientfactories.append(DummyClientProtocolFactory(takers[i]))
             clientfactory = clientfactories[0]
             clientconn = reactor.connectTCP("localhost", 28184,
                                             clientfactories[0])
             self.addCleanup(clientconn.disconnect)
示例#4
0
def main():
    parser = OptionParser(
        usage='usage: %prog [options]',
        description='Runs a webservice which shows the orderbook.')
    add_base_options(parser)
    parser.add_option('-H',
                      '--host',
                      action='store',
                      type='string',
                      dest='host',
                      default='localhost',
                      help='hostname or IP to bind to, default=localhost')
    parser.add_option('-p',
                      '--port',
                      action='store',
                      type='int',
                      dest='port',
                      help='port to listen on, default=62601',
                      default=62601)
    (options, args) = parser.parse_args()
    load_program_config(config_path=options.datadir)
    hostport = (options.host, options.port)
    mcs = [ObIRCMessageChannel(c) for c in get_irc_mchannels()]
    mcc = MessageChannelCollection(mcs)
    mcc.set_nick(get_dummy_nick())
    taker = ObBasic(mcc, hostport)
    log.info("Starting ob-watcher")
    mcc.run()
示例#5
0
def main():
    parser = OptionParser(
        usage='usage: %prog [options] wallet_file_name',
        description='Create a wallet with the given wallet name')
    (options, args) = parser.parse_args()

    load_program_config(config_path="/data/.joinmarket")
    with open(os.path.join(jm_single().datadir, "jm-wallet-seed"),
              "r") as file:
        words = file.read().replace('\n', '')
        words.strip()
    with open(os.path.join(jm_single().datadir, "jm-wallet-password"),
              "r") as file:
        password = file.read().replace('\n', '').encode("utf-8")
    entropy = SegwitLegacyWallet.entropy_from_mnemonic(str(words))
    wallet_root_path = os.path.join(jm_single().datadir, "wallets")
    # add wallet as first argument
    wallet_name = os.path.join(wallet_root_path, args[0])
    wallet = create_wallet(wallet_name,
                           password,
                           4,
                           SegwitLegacyWallet,
                           entropy=entropy,
                           entropy_extension=None)
    jmprint("recovery_seed:{}".format(wallet.get_mnemonic_words()[0]),
            "important")
    wallet.close()
示例#6
0
def main():
    parser = OptionParser(
        usage=
        'usage: %prog [options] utxo destaddr1 destaddr2 ..',
        description="For creating multiple utxos from one (for commitments in JM)."
                    "Provide a utxo in form txid:N that has some unspent coins;"
                    "Specify a list of destination addresses and the coins will"
                    "be split equally between them (after bitcoin fees)."

                    "You'll be prompted to enter the private key for the utxo"
                    "during the run; it must be in WIF compressed format."
                    "After the transaction is completed, the utxo strings for"

                    "the new outputs will be shown."
                    "Note that these utxos will not be ready for use as external"

                    "commitments in Joinmarket until 5 confirmations have passed."
                    " BE CAREFUL about handling private keys!"
                    " Don't do this in insecure environments."
                    " Also note this ONLY works for standard (p2pkh) utxos."
    )
    parser.add_option(
        '-v',
        '--validate-utxos',
        action='store_true',
        dest='validate',
        help='validate the utxos and pubkeys provided against the blockchain',
        default=False
    )
    parser.add_option(
        '-o',
        '--validate-only',
        action='store_true',
        dest='vonly',
        help='only validate the provided utxos (file or command line), not add',
        default=False
    )
    (options, args) = parser.parse_args()
    load_program_config()
    if len(args) < 2:
        quit(parser, 'Invalid syntax')
    u = args[0]
    priv = raw_input(
        'input private key for ' + u + ', in WIF compressed format : ')
    u, priv = get_utxo_info(','.join([u, priv]))
    if not u:
        quit(parser, "Failed to parse utxo info: " + u)
    destaddrs = args[1:]
    for d in destaddrs:
        if not validate_address(d):
            quit(parser, "Address was not valid; wrong network?: " + d)
    txsigned = sign(u, priv, destaddrs)
    log.debug("Got signed transaction:\n" + txsigned)
    log.debug("Deserialized:")
    log.debug(pformat(btc.deserialize(txsigned)))
    if raw_input('Would you like to push to the network? (y/n):')[0] != 'y':
        log.info("You chose not to broadcast the transaction, quitting.")
        return
    jm_single().bc_interface.pushtx(txsigned)
def receive_payjoin_main():
    parser = OptionParser(usage='usage: %prog [options] [wallet file] [amount-to-receive]')
    add_base_options(parser)
    parser.add_option('-P', '--hs-port', action='store', type='int',
                      dest='hsport', default=80,
                      help='port on which to serve the ephemeral hidden service.')
    parser.add_option('-g', '--gap-limit', action='store', type="int",
                      dest='gaplimit', default=6,
                      help='gap limit for wallet, default=6')
    parser.add_option('-m', '--mixdepth', action='store', type='int',
                      dest='mixdepth', default=0,
                      help="mixdepth to source coins from")
    parser.add_option('-a',
                      '--amtmixdepths',
                      action='store',
                      type='int',
                      dest='amtmixdepths',
                      help='number of mixdepths in wallet, default 5',
                      default=5)

    (options, args) = parser.parse_args()
    if len(args) < 2:
        parser.error('Needs a wallet, and a receiving amount in bitcoins or satoshis')
        sys.exit(EXIT_ARGERROR)
    wallet_name = args[0]
    try:
        # amount is stored internally in sats, but will be decimal in URL.
        bip78_amount = amount_to_sat(args[1])
    except:
        parser.error("Invalid receiving amount passed: " + bip78_amount)
        sys.exit(EXIT_FAILURE)
    if bip78_amount < 0:
        parser.error("Receiving amount must be a positive number")
        sys.exit(EXIT_FAILURE)
    load_program_config(config_path=options.datadir)

    check_regtest()

    wallet_path = get_wallet_path(wallet_name, None)
    max_mix_depth = max([options.mixdepth, options.amtmixdepths - 1])
    wallet = open_test_wallet_maybe(
        wallet_path, wallet_name, max_mix_depth,
        wallet_password_stdin=options.wallet_password_stdin,
        gap_limit=options.gaplimit)
    wallet_service = WalletService(wallet)

    while not wallet_service.synced:
        wallet_service.sync_wallet(fast=not options.recoversync)
    wallet_service.startService()
    # having enforced wallet sync, we can check if we have coins
    # to do payjoin in the mixdepth
    if wallet_service.get_balance_by_mixdepth()[options.mixdepth] == 0:
        jlog.error("Cannot do payjoin from mixdepth " + str(
            options.mixdepth) + ", no coins. Shutting down.")
        sys.exit(EXIT_ARGERROR)
    receiver_manager = JMBIP78ReceiverManager(wallet_service, options.mixdepth,
                                    bip78_amount, options.hsport)
    receiver_manager.start_pj_server_and_tor()
    reactor.run()
def get_ob():
    load_program_config()
    dm = DummyDaemon()
    mc = DummyMC(get_irc_mchannels()[0], "test", dm)
    ob = OrderbookWatch()
    ob.on_welcome = on_welcome
    ob.set_msgchan(mc)
    return ob
 def setUp(self):
     load_program_config()
     jm_single().maker_timeout_sec = 1
     self.port = reactor.listenTCP(28184, JMDaemonTestServerProtocolFactory())
     self.addCleanup(self.port.stopListening)
     clientconn = reactor.connectTCP("localhost", 28184,
                                     JMTestClientProtocolFactory())
     self.addCleanup(clientconn.disconnect)
示例#10
0
def test_config_get_irc_channel():
    load_program_config()
    channel = "dummy"
    assert get_config_irc_channel(channel) == "#dummy-test"
    jm_single().config.set("BLOCKCHAIN", "network", "mainnet")
    assert get_config_irc_channel(channel) == "#dummy"
    get_irc_mchannels()
    load_program_config()
示例#11
0
def setup_walletservice(request):
    load_program_config()
    old_reuse_freeze_val = jm_single().config.getint("POLICY",
                                                     "max_sats_freeze_reuse")

    def reset_config():
        set_freeze_reuse_config(old_reuse_freeze_val)

    request.addfinalizer(reset_config)
示例#12
0
def test_imported_privkey(setup_wallets):
    for n in ["mainnet", "testnet"]:
        privkey = "7d998b45c219a1e38e99e7cbd312ef67f77a455a9b50c730c27f02c6f730dfb401"
        jm_single().config.set("BLOCKCHAIN", "network", n)
        password = "******"
        password_key = bitcoin.bin_dbl_sha256(password)
        wifprivkey = bitcoin.wif_compressed_privkey(privkey, get_p2pk_vbyte())
        #mainnet is "L1RrrnXkcKut5DEMwtDthjwRcTTwED36thyL1DebVrKuwvohjMNi"
        #to verify use from_wif_privkey and privkey_to_address
        if n == "mainnet":
            iaddr = "1LDsjB43N2NAQ1Vbc2xyHca4iBBciN8iwC"
        else:
            iaddr = "mzjq2E92B3oRB7yDKbwM7XnPaAnKfRERw2"
        privkey_bin = bitcoin.from_wif_privkey(
            wifprivkey, vbyte=get_p2pk_vbyte()).decode('hex')[:-1]
        encrypted_privkey = encryptData(password_key, privkey_bin)
        encrypted_privkey_bad = encryptData(password_key, privkey_bin[:6])
        walletdir = "wallets"
        testwalletname = "test" + n
        pathtowallet = os.path.join(walletdir, testwalletname)
        seed = bitcoin.sha256("\xaa" * 64)[:32]
        encrypted_seed = encryptData(password_key, seed.decode('hex'))
        timestamp = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
        for ep in [encrypted_privkey, encrypted_privkey_bad]:
            walletfilejson = {
                'creator':
                'joinmarket project',
                'creation_time':
                timestamp,
                'encrypted_seed':
                encrypted_seed.encode('hex'),
                'network':
                n,
                'index_cache': [[0, 0]] * 5,
                'imported_keys': [{
                    'encrypted_privkey': ep.encode('hex'),
                    'mixdepth': 0
                }]
            }
            walletfile = json.dumps(walletfilejson)
            if not os.path.exists(walletdir):
                os.makedirs(walletdir)
            with open(pathtowallet, "wb") as f:
                f.write(walletfile)
            if ep == encrypted_privkey_bad:
                with pytest.raises(Exception) as e_info:
                    Wallet(testwalletname, password, 5, 6, False, False)
                continue
            newwallet = Wallet(testwalletname, password, 5, 6, False, False)
            assert newwallet.seed == seed
            #test accessing the key from the addr
            assert newwallet.get_key_from_addr(
                iaddr) == bitcoin.from_wif_privkey(wifprivkey,
                                                   vbyte=get_p2pk_vbyte())
            if n == "testnet":
                jm_single().bc_interface.sync_wallet(newwallet)
    load_program_config()
def setup_blockr(request):
    def blockr_teardown():
        jm_single().config.set("BLOCKCHAIN", "blockchain_source", "regtest")
        jm_single().config.set("BLOCKCHAIN", "network", "testnet")

    request.addfinalizer(blockr_teardown)
    load_program_config()
    jm_single().config.set("BLOCKCHAIN", "blockchain_source", "blockr")
    jm_single().bc_interface = BlockrInterface(True)
示例#14
0
def setup_cj():
    load_program_config()
    jm_single().config.set('POLICY', 'tx_broadcast', 'self')
    jm_single().bc_interface.tick_forward_chain_interval = 5
    jm_single().bc_interface.simulate_blocks()
    yield None
    # teardown
    for dc in reactor.getDelayedCalls():
        dc.cancel()
def createcmtdata(request):
    def cmtdatateardown():
        shutil.rmtree("cmtdata")
    request.addfinalizer(cmtdatateardown)
    if not os.path.exists("cmtdata"):
            os.makedirs("cmtdata")
    load_program_config()
    jm_single().bc_interface = DummyBlockchainInterface()
    jm_single().config.set("BLOCKCHAIN", "network", "testnet")
示例#16
0
def test_pushtx_errors(setup_wallets):
    """Ensure pushtx fails return False
    """
    badtxhex = "aaaa"
    assert not jm_single().bc_interface.pushtx(badtxhex)
    #Break the authenticated jsonrpc and try again
    jm_single().bc_interface.jsonRpc.port = 18333
    assert not jm_single().bc_interface.pushtx(t_raw_signed_tx)
    #rebuild a valid jsonrpc inside the bci
    load_program_config()
示例#17
0
def setup_cj():
    load_program_config()
    jm_single().config.set('POLICY', 'tx_broadcast', 'self')
    jm_single().bc_interface.tick_forward_chain_interval = 5
    jm_single().bc_interface.simulate_blocks()
    #see note in cryptoengine.py:
    cryptoengine.BTC_P2WPKH.VBYTE = 100
    yield None
    # teardown
    for dc in reactor.getDelayedCalls():
        dc.cancel()
def main():
    parser = OptionParser(
        usage='usage: %prog [options] utxo destaddr1 destaddr2 ..',
        description=description,
        formatter=IndentedHelpFormatterWithNL())
    parser.add_option(
        '-t',
        '--utxo-address-type',
        action='store',
        dest='utxo_address_type',
        help=
        ('type of address of coin being spent - one of "p2pkh", "p2wpkh", "p2sh-p2wpkh". '
         'No other scriptpubkey types (e.g. multisig) are supported. If not set, we default '
         'to what is in joinmarket.cfg.'),
        default="")
    add_base_options(parser)
    (options, args) = parser.parse_args()
    load_program_config(config_path=options.datadir)
    if len(args) < 2:
        quit(parser, 'Invalid syntax')
    u = args[0]
    priv = input('input private key for ' + u +
                 ', in WIF compressed format : ')
    u, priv = get_utxo_info(','.join([u, priv]))
    if not u:
        quit(parser, "Failed to parse utxo info: " + u)
    destaddrs = args[1:]
    for d in destaddrs:
        if not validate_address(d):
            quit(parser, "Address was not valid; wrong network?: " + d)
    success, utxo = utxostr_to_utxo(u)
    if not success:
        quit(parser, "Failed to load utxo from string: " + utxo)
    if options.utxo_address_type == "":
        if jm_single().config.get("POLICY", "segwit") == "false":
            utxo_address_type = "p2pkh"
        elif jm_single().config.get("POLICY", "native") == "false":
            utxo_address_type = "p2sh-p2wpkh"
        else:
            utxo_address_type = "p2wpkh"
    else:
        utxo_address_type = options.utxo_address_type
    txsigned = sign(utxo, priv, destaddrs, utxo_address_type)
    if not txsigned:
        log.info(
            "Transaction signing operation failed, see debug messages for details."
        )
        return
    log.info("Got signed transaction:\n" + bintohex(txsigned.serialize()))
    log.info(btc.human_readable_transaction(txsigned))
    if input('Would you like to push to the network? (y/n):')[0] != 'y':
        log.info("You chose not to broadcast the transaction, quitting.")
        return
    jm_single().bc_interface.pushtx(txsigned.serialize())
示例#19
0
def test_blockchain_sources():
    load_program_config()
    for src in ["electrum", "dummy"]:
        jm_single().config.set("BLOCKCHAIN", "blockchain_source", src)
        if src == "electrum":
            jm_single().config.set("BLOCKCHAIN", "network", "mainnet")
        if src == "dummy":
            with pytest.raises(ValueError) as e_info:
                get_blockchain_interface_instance(jm_single().config)
        else:
            get_blockchain_interface_instance(jm_single().config)
    load_program_config()
示例#20
0
def setup_taker(request):
    def clean():
        from twisted.internet import reactor
        for dc in reactor.getDelayedCalls():
            dc.cancel()
    request.addfinalizer(clean)
    def cmtdatateardown():
        shutil.rmtree("cmtdata")
    request.addfinalizer(cmtdatateardown)
    if not os.path.exists("cmtdata"):
            os.makedirs("cmtdata")
    load_program_config()
    jm_single().bc_interface = DummyBlockchainInterface()
    jm_single().config.set("BLOCKCHAIN", "network", "testnet")
示例#21
0
def test_get_schedule():
    load_program_config()
    tsf = "schedulefortesting"
    for s in [valids, invalids1, invalids2, invalids3, invalids4]:
        if os.path.exists(tsf):
            os.remove(tsf)
        with open(tsf, "wb") as f:
            f.write(s)
        result = get_schedule(tsf)
        if s == valids:
            assert result[0]
            assert len(result[1]) == 2
        else:
            assert not result[0]
示例#22
0
def test_get_utxo_info():
    load_program_config()
    jm_single().config.set("BLOCKCHAIN", "network", "mainnet")
    dbci = DummyBlockchainInterface()
    privkey = "L1RrrnXkcKut5DEMwtDthjwRcTTwED36thyL1DebVrKuwvohjMNi"
    #to verify use from_wif_privkey and privkey_to_address
    iaddr = "1LDsjB43N2NAQ1Vbc2xyHca4iBBciN8iwC"
    fakeutxo = "aa" * 32 + ":08"

    fake_query_results = [{
        'value': 200000000,
        'address': iaddr,
        'utxo': fakeutxo,
        'confirms': 20
    }]
    dbci.insert_fake_query_results(fake_query_results)
    jm_single().bc_interface = dbci
    u, priv = get_utxo_info(fakeutxo + "," + privkey)
    assert u == fakeutxo
    assert priv == privkey
    #invalid format
    with pytest.raises(Exception) as e_info:
        u, priv = get_utxo_info(fakeutxo + privkey)
    #invalid index
    fu2 = "ab" * 32 + ":00004"
    with pytest.raises(Exception) as e_info:
        u, priv = get_utxo_info(fu2 + "," + privkey)
    #invalid privkey
    p2 = privkey[:-1] + 'j'
    with pytest.raises(Exception) as e_info:
        u, priv = get_utxo_info(fakeutxo + "," + p2)

    utxodatas = [(fakeutxo, privkey)]
    retval = validate_utxo_data(utxodatas, False)
    assert retval
    #try to retrieve
    retval = validate_utxo_data(utxodatas, True)
    assert retval[0] == (fakeutxo, 200000000)
    fake_query_results[0]['address'] = "fakeaddress"
    dbci.insert_fake_query_results(fake_query_results)
    #validate should fail for wrong address
    retval = validate_utxo_data(utxodatas, False)
    assert not retval
    #remove fake query result and trigger not found
    dbci.fake_query_results = None
    dbci.setQUSFail(True)
    retval = validate_utxo_data(utxodatas, False)
    assert not retval
    dbci.setQUSFail(False)
示例#23
0
    def __init__(self, balances):
        """Creates the wallet, setting the balances of the mixdepths
        as given by the array.  (And the number of mixdepths from the array
        elements."""

        load_program_config()

        storage = VolatileStorage()
        super(CustomUtxoWallet,
              self).initialize(storage,
                               get_network(),
                               max_mixdepth=len(balances) - 1)
        super(CustomUtxoWallet, self).__init__(storage)

        for m, b in enumerate(balances):
            self.add_utxo_at_mixdepth(m, b)
def main():
    global bond_exponent
    parser = OptionParser(
        usage='usage: %prog [options]',
        description='Runs a webservice which shows the orderbook.')
    add_base_options(parser)
    parser.add_option('-H',
                      '--host',
                      action='store',
                      type='string',
                      dest='host',
                      default='localhost',
                      help='hostname or IP to bind to, default=localhost')
    parser.add_option('-p',
                      '--port',
                      action='store',
                      type='int',
                      dest='port',
                      help='port to listen on, default=62601',
                      default=62601)
    (options, args) = parser.parse_args()
    load_program_config(config_path=options.datadir)
    # needed to display notional units of FB valuation
    bond_exponent = jm_single().config.get("POLICY", "bond_value_exponent")
    try:
        float(bond_exponent)
    except ValueError:
        log.error("Invalid entry for bond_value_exponent, should be decimal "
                  "number: {}".format(bond_exponent))
        sys.exit(EXIT_FAILURE)
    check_and_start_tor()
    hostport = (options.host, options.port)
    mcs = []
    chan_configs = get_mchannels(mode="PASSIVE")
    for c in chan_configs:
        if "type" in c and c["type"] == "onion":
            mcs.append(OnionMessageChannel(c))
        else:
            # default is IRC; TODO allow others
            mcs.append(IRCMessageChannel(c))
    IRCMessageChannel.on_privmsg = on_privmsg
    OnionMessageChannel.on_privmsg = on_privmsg
    mcc = MessageChannelCollection(mcs)
    mcc.set_nick(get_dummy_nick())
    taker = ObBasic(mcc, hostport)
    log.info("Starting ob-watcher")
    mcc.run()
    def setUp(self):
        load_program_config()
        print(get_irc_mchannels()[0])
        jm_single().maker_timeout_sec = 1
        dm, mc, mcc = getmc("irc_publisher")
        dm2, mc2, mcc2 = getmc("irc_receiver")
        mcc.run()
        mcc2.run()

        def cb(m):
            #don't try to reconnect
            m.give_up = True
            m.tcp_connector.disconnect()

        self.addCleanup(cb, mc)
        self.addCleanup(cb, mc2)
        #test_junk_messages()
        print("Got here")
def setup_podle(request):
    load_program_config()
    if not os.path.exists("cmtdata"):
        os.mkdir("cmtdata")
    prev_commits = False
    #back up any existing commitments
    pcf = get_commitment_file()
    log.debug("Podle file: " + pcf)
    if os.path.exists(pcf):
        os.rename(pcf, pcf + ".bak")
        prev_commits = True
    def teardown():
        if prev_commits:
            os.rename(pcf + ".bak", pcf)
        else:
            if os.path.exists(pcf):
                os.remove(pcf)
    request.addfinalizer(teardown)
示例#27
0
def test_query_utxo_set(setup_wallets):
    load_program_config()
    jm_single().bc_interface.tick_forward_chain_interval = 1
    wallet = create_wallet_for_sync([2, 3, 0, 0, 0],
                                    ["wallet4utxo.json", "4utxo", [2, 3]])
    sync_wallet(wallet, fast=True)
    txid = do_tx(wallet, 90000000)
    txid2 = do_tx(wallet, 20000000)
    print("Got txs: ", txid, txid2)
    res1 = jm_single().bc_interface.query_utxo_set(txid + ":0", includeunconf=True)
    res2 = jm_single().bc_interface.query_utxo_set(
        [txid + ":0", txid2 + ":1"],
        includeconf=True, includeunconf=True)
    assert len(res1) == 1
    assert len(res2) == 2
    assert all([x in res1[0] for x in ['script', 'address', 'value']])
    assert not 'confirms' in res1[0]
    assert 'confirms' in res2[0]
    assert 'confirms' in res2[1]
    res3 = jm_single().bc_interface.query_utxo_set("ee" * 32 + ":25")
    assert res3 == [None]
示例#28
0
def main():
    parser = OptionParser(
    usage='usage: %prog [options] wallet_file_name password',
    description='Create a wallet with the given wallet name and password.')
    (options, args) = parser.parse_args()

    # Load up defaults
    load_program_config(config_path='/data/.joinmarket')
    wallet_root_path = os.path.join(jm_single().datadir, "wallets")
    # get wallet from first argument
    wallet_name = os.path.join(wallet_root_path, args[0])
    wallet = create_wallet(wallet_name, args[1].encode("utf-8"), 4, SegwitLegacyWallet)
    # Open file for writing
    seedfile = open(os.path.join(jm_single().datadir, "jm-wallet-seed"), "w")
    seedfile.write(wallet.get_mnemonic_words()[0])
    seedfile.write("\n")
    seedfile.close()

    jmprint("recovery_seed:{}"
         .format(wallet.get_mnemonic_words()[0]), "important")
    wallet.close()
def main():
    parser = OptionParser(
        usage='usage: %prog [options] wallet_file_name [password]',
        description='Create a wallet with the given wallet name and password.')
    add_base_options(parser)
    parser.add_option(
        '--recovery-seed-file',
        dest='seed_file',
        default=None,
        help=
        ('File containing a mnemonic recovery phrase. If provided, the wallet '
         'is recovered from this seed instead of being newly generated.'))
    (options, args) = parser.parse_args()
    wallet_name = args[0]
    if options.wallet_password_stdin:
        password = wallet_utils.read_password_stdin()
    else:
        assert len(
            args
        ) > 1, "must provide password via stdin (see --help), or as second argument."
        password = args[1].encode("utf-8")
    seed = options.seed_file and Path(options.seed_file).read_text().rstrip()

    load_program_config(config_path=options.datadir)
    wallet_root_path = os.path.join(jm_single().datadir, "wallets")
    wallet_path = os.path.join(wallet_root_path, wallet_name)
    if jm_single().config.get("POLICY", "native") == "true":
        walletclass = SegwitWalletFidelityBonds
    else:
        # Fidelity Bonds are not available for segwit legacy wallets
        walletclass = SegwitLegacyWallet
    entropy = seed and SegwitLegacyWallet.entropy_from_mnemonic(seed)
    wallet = create_wallet(wallet_path,
                           password,
                           wallet_utils.DEFAULT_MIXDEPTH,
                           walletclass,
                           entropy=entropy)
    jmprint("recovery_seed:{}".format(wallet.get_mnemonic_words()[0]),
            "important")
    wallet.close()
示例#30
0
def test_load_config(tmpdir):
    load_program_config(bs="regtest")
    jm_single().config_location = "joinmarket.cfg"
    with pytest.raises(SystemExit):
        load_program_config(config_path=str(tmpdir), bs="regtest")
    jm_single().config_location = "joinmarket.cfg"
    load_program_config()
示例#31
0
 def load_config(self, window):
     """Load/instantiate the joinmarket config file
     in electrum's home directory/joinmarket (e.g. ~/.electrum/joinmarket
     Also load/instantiate the logs/ subdirectory for bot logs,
     and the cmtdata/ directory for commitments storage.
     Create and set the commitments.json file.
     """
     try:
         jm_subdir = os.path.join(window.config.path, "joinmarket")
         if not os.path.exists(jm_subdir):
             os.makedirs(jm_subdir)
         cmttools_dir = os.path.join(jm_subdir, "cmtdata")
         if not os.path.exists(cmttools_dir):
             os.makedirs(cmttools_dir)
         set_commitment_file(os.path.join(cmttools_dir, "commitments.json"))
         self.config_location = os.path.join(jm_subdir, "joinmarket.cfg")
         self.logs_location = os.path.join(jm_subdir, "logs")
         load_program_config(jm_subdir, "electrum")
         if TESTNET:
             jm_single().config.set("BLOCKCHAIN", "network", "testnet")
             log.info('working with testnet')
         else:
             jm_single().config.set("BLOCKCHAIN", "network", "mainnet")
             log.info('working with mainnet')
     except Exception as e:
         log.info("thrown: " + repr(e))
         JMQtMessageBox(window,
                        "\n".join([
                            "The joinmarket config failed to load.",
                            "Make sure that blockchain_source = electrum",
                            "is set in the joinmarket.cfg file."]),
                        mbtype='warn',
                        title="Error")
         return
     if not os.path.exists(self.logs_location):
         os.makedirs(self.logs_location)
     update_config_for_gui()