Create a new wallet from an extended pubkey (xpub... for BTC)

    You can delete the wallet with the delete_wallet method below
16870
def create_hd_wallet(wallet_name, xpubkey, api_key, subchain_indices=[], coin_symbol='btc'):
    '''
    
    '''
    inferred_coin_symbol = coin_symbol_from_mkey(mkey=xpubkey)
    if inferred_coin_symbol:
        assert inferred_coin_symbol == coin_symbol
    assert api_key, 'api_key required'
    assert len(wallet_name) <= 25, wallet_name

    data = {
            'name': wallet_name,
            'extended_public_key': xpubkey,
            }
    params = {'token': api_key}

    if subchain_indices:
        data['subchain_indexes'] = subchain_indices

    url = make_url(coin_symbol, **dict(wallets='hd'))

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r)
397003
public Protos.Wallet walletToProto(Wallet wallet) {
        Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
        walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
        if (wallet.getDescription() != null) {
            walletBuilder.setDescription(wallet.getDescription());
        }

        for (WalletTransaction wtx : wallet.getWalletTransactions()) {
            Protos.Transaction txProto = makeTxProto(wtx);
            walletBuilder.addTransaction(txProto);
        }

        walletBuilder.addAllKey(wallet.serializeKeyChainGroupToProtobuf());

        for (Script script : wallet.getWatchedScripts()) {
            Protos.Script protoScript =
                    Protos.Script.newBuilder()
                            .setProgram(ByteString.copyFrom(script.getProgram()))
                            .setCreationTimestamp(script.getCreationTimeSeconds() * 1000)
                            .build();

            walletBuilder.addWatchedScript(protoScript);
        }

        // Populate the lastSeenBlockHash field.
        Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash();
        if (lastSeenBlockHash != null) {
            walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
            walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
        }
        if (wallet.getLastBlockSeenTimeSecs() > 0)
            walletBuilder.setLastSeenBlockTimeSecs(wallet.getLastBlockSeenTimeSecs());

        // Populate the scrypt parameters.
        KeyCrypter keyCrypter = wallet.getKeyCrypter();
        if (keyCrypter == null) {
            // The wallet is unencrypted.
            walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED);
        } else {
            // The wallet is encrypted.
            walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType());
            if (keyCrypter instanceof KeyCrypterScrypt) {
                KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter;
                walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters());
            } else {
                // Some other form of encryption has been specified that we do not know how to persist.
                throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this.");
            }
        }

        if (wallet.getKeyRotationTime() != null) {
            long timeSecs = wallet.getKeyRotationTime().getTime() / 1000;
            walletBuilder.setKeyRotationTime(timeSecs);
        }

        populateExtensions(wallet, walletBuilder);

        for (Map.Entry<String, ByteString> entry : wallet.getTags().entrySet()) {
            Protos.Tag.Builder tag = Protos.Tag.newBuilder().setTag(entry.getKey()).setData(entry.getValue());
            walletBuilder.addTags(tag);
        }

        // Populate the wallet version.
        walletBuilder.setVersion(wallet.getVersion());

        return walletBuilder.build();
    }
124017
function createWallet(xPubKey, account, arrWalletDefinitionTemplate, walletName, isSingleAddress, handleWallet){
	var wallet = crypto.createHash("sha256").update(xPubKey, "utf8").digest("base64");
	console.log('will create wallet '+wallet);
	var arrDeviceAddresses = getDeviceAddresses(arrWalletDefinitionTemplate);
	addWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, function(){
		handleWallet(wallet);
		if (arrDeviceAddresses.length === 1) // single sig
			return;
		console.log("will send offers");
		// this continues in parallel while the callback handleWallet was already called
		// We need arrOtherCosigners to make sure all cosigners know the pubkeys of all other cosigners, even when they were not paired.
		// For example, there are 3 cosigners: A (me), B, and C. A is paired with B, A is paired with C, but B is not paired with C.
		device.readCorrespondentsByDeviceAddresses(arrDeviceAddresses, function(arrOtherCosigners){
			if (arrOtherCosigners.length !== arrDeviceAddresses.length - 1)
				throw Error("incorrect length of other cosigners");
			arrDeviceAddresses.forEach(function(device_address){
				if (device_address === device.getMyDeviceAddress())
					return;
				console.log("sending offer to "+device_address);
				sendOfferToCreateNewWallet(device_address, wallet, arrWalletDefinitionTemplate, walletName, arrOtherCosigners, isSingleAddress, null);
				sendMyXPubKey(device_address, wallet, xPubKey);
			});
		});
	});
}
1253401
async def post(self, public_key):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		try:
			body = json.loads(self.request.body)
		except:
			self.set_status(400)
			self.write({"error":400, "reason":"Unexpected data format. JSON required"})
			raise tornado.web.Finish
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]

		cid = message.get("cid")
		review = message.get("review")
		rating = message.get("rating")
		coinid = message.get("coinid")

		if not all([cid, rating, review]):
			self.set_status(400)
			self.write({"error":400, "reason":"Missed required fields"})

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		else:
			self.set_status(400)
			self.write({"error":400, "reason":"Invalid coinid"})
			raise tornado.web.Finish 

		buyer_address = self.account.validator[coinid](public_key)

		review = await self.account.blockchain.addreview(cid=int(cid),buyer_address=buyer_address,
														stars=int(rating), review=review)
		await self.account.setreview(cid=cid, txid=review["result"]["txid"], coinid=coinid)

		self.write({"cid":cid, "review":review, "rating":rating})
167971
def create(curve, data):
    
    ec_key = libcrypto.EC_KEY_new_by_curve_name(curve.nid)
    if ec_key is None:
        raise PKeyError("EC_KEY_new_by_curvename")
    group = libcrypto.EC_KEY_get0_group(ec_key)
    if group is None:
        raise PKeyError("EC_KEY_get0_group")
    libcrypto.EC_GROUP_set_asn1_flag(group, 1)
    raw_key = libcrypto.BN_new()
    if isinstance(data, int):
        libcrypto.BN_hex2bn(byref(raw_key), hex(data))
    else:
        if raw_key is None:
            raise PKeyError("BN_new")
        if libcrypto.BN_bin2bn(data, len(data), raw_key) is None:
            raise PKeyError("BN_bin2bn")
    ctx = libcrypto.BN_CTX_new()
    if ctx is None:
        raise PKeyError("BN_CTX_new")
    order = libcrypto.BN_new()
    if order is None:
        raise PKeyError("BN_new")
    priv_key = libcrypto.BN_new()
    if priv_key is None:
        raise PKeyError("BN_new")
    if libcrypto.EC_GROUP_get_order(group, order, ctx) <= 0:
        raise PKeyError("EC_GROUP_get_order")
    if libcrypto.BN_nnmod(priv_key, raw_key, order, ctx) <= 0:
        raise PKeyError("BN_nnmod")
    if libcrypto.EC_KEY_set_private_key(ec_key, priv_key) <= 0:
        raise PKeyError("EC_KEY_set_private_key")
    pub_key = libcrypto.EC_POINT_new(group)
    if pub_key is None:
        raise PKeyError("EC_POINT_new")
    if libcrypto.EC_POINT_mul(group, pub_key, priv_key, None, None, ctx) <= 0:
        raise PKeyError("EC_POINT_mul")
    if libcrypto.EC_KEY_set_public_key(ec_key, pub_key) <= 0:
        raise PKeyError("EC_KEY_set_public_key")
    libcrypto.BN_free(raw_key)
    libcrypto.BN_free(order)
    libcrypto.BN_free(priv_key)
    libcrypto.BN_CTX_free(ctx)
    pkey = libcrypto.EVP_PKEY_new()
    if pkey is None:
        raise PKeyError("EVP_PKEY_new")
    if libcrypto.EVP_PKEY_set1_EC_KEY(pkey, ec_key) <= 0:
        raise PKeyError("EVP_PKEY_set1_EC_KEY")
    libcrypto.EC_KEY_free(ec_key)
    return PKey(ptr=pkey, cansign=True)
450073
async def create(self) -> None:
        

        LOGGER.debug('Wallet.create >>>')

        try:
            await wallet.create_wallet(
                config=json.dumps(self.config),
                credentials=json.dumps(self.access_creds))
            LOGGER.info('Created wallet %s', self.name)
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletAlreadyExistsError:
                LOGGER.debug('Wallet.create <!< Wallet %s already exists', self.name)
                raise ExtantWallet('Wallet {} already exists'.format(self.name))
            LOGGER.debug(
                'Wallet.create <!< indy error code %s on creation of wallet %s',
                x_indy.error_code,
                self.name)
            raise

        auto_remove = self.auto_remove
        self.auto_remove = False  # defer past this creation process
        async with self:
            did_info = await self.create_local_did(
                self._von_config.get('seed', None),
                self._von_config.get('did', None),
                {'anchor': True})
            self.did = did_info.did
            self.verkey = did_info.verkey
            if 'link_secret_label' in self._von_config:
                await self.create_link_secret(self._von_config['link_secret_label'])
        self.auto_remove = auto_remove

        LOGGER.debug('Wallet.create <<<')
973623
def get_wallet_balance(wallet_name, api_key, omit_addresses=False, coin_symbol='btc'):
    '''
    
    '''
    assert is_valid_coin_symbol(coin_symbol)
    assert api_key
    assert len(wallet_name) <= 25, wallet_name
    assert isinstance(omit_addresses, bool), omit_addresses

    params = {'token': api_key}
    if omit_addresses:
        params['omitWalletAddresses'] = 'true'

    url = make_url(coin_symbol, 'addrs/{}/balance'.format(wallet_name))

    r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r)
418742
function TXDB(wallet) {
  if (!(this instanceof TXDB))
    return new TXDB(wallet);

  this.wallet = wallet;
  this.walletdb = wallet.db;
  this.db = wallet.db.db;
  this.logger = wallet.db.logger;
  this.network = wallet.db.network;
  this.options = wallet.db.options;
  this.coinCache = new LRU(10000);

  this.locked = new Set();
  this.state = null;
  this.pending = null;
  this.events = [];
}
241766
def delete_forwarding_address(payment_id, coin_symbol='btc', api_key=None):
    '''
    
    '''

    assert payment_id, 'payment_id required'
    assert is_valid_coin_symbol(coin_symbol)
    assert api_key, 'api_key required'

    params = {'token': api_key}

    url = make_url(**dict(payments=payment_id))

    r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r, allow_204=True)
145352
function WalletOptions(options) {
  if (!(this instanceof WalletOptions))
    return new WalletOptions(options);

  this.network = Network.primary;
  this.logger = Logger.global;
  this.workers = null;
  this.client = null;
  this.feeRate = 0;

  this.prefix = null;
  this.location = null;
  this.db = 'memory';
  this.maxFiles = 64;
  this.cacheSize = 16 << 20;
  this.compression = true;
  this.bufferKeys = layout.binary;

  this.spv = false;
  // this.witness = false; cfc
  this.witness = true; // ctl
  this.checkpoints = false;
  this.startHeight = 0;
  this.keepBlocks = this.network.block.keepBlocks;
  this.wipeNoReally = false;
  this.apiKey = null;
  this.walletAuth = false;
  this.noAuth = false;
  this.ssl = false;
  this.host = '127.0.0.1';
  this.port = this.network.rpcPort + 2;
  this.listen = false;

  if (options)
    this.fromOptions(options);
}
627527
def btc_make_p2wpkh_address( pubkey_hex ):
    
    pubkey_hex = keylib.key_formatting.compress(pubkey_hex)
    hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex'))
    return segwit_addr_encode(hash160_bin)
201564
@VisibleForTesting
    Block createNextBlockWithCoinbase(long version, byte[] pubKey, final int height) {
        return createNextBlock(null, version, (TransactionOutPoint) null,
                               Utils.currentTimeSeconds(), pubKey, FIFTY_COINS, height);
    }
224481
def dump_private_keys_or_addrs_chooser(wallet_obj):
    '''
    
    '''

    if wallet_obj.private_key:
        puts('Which private keys and addresses do you want?')
    else:
        puts('Which addresses do you want?')
    with indent(2):
        puts(colored.cyan('1: Active - have funds to spend'))
        puts(colored.cyan('2: Spent - no funds to spend (because they have been spent)'))
        puts(colored.cyan('3: Unused - no funds to spend (because the address has never been used)'))
        puts(colored.cyan('0: All (works offline) - regardless of whether they have funds to spend (super advanced users only)'))
        puts(colored.cyan('\nb: Go Back\n'))
    choice = choice_prompt(
            user_prompt=DEFAULT_PROMPT,
            acceptable_responses=[0, 1, 2, 3],
            default_input='1',
            show_default=True,
            quit_ok=True,
            )

    if choice is False:
        return

    if choice == '1':
        return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=False, used=True)
    elif choice == '2':
        return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=True, used=True)
    elif choice == '3':
        return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=None, used=False)
    elif choice == '0':
        return dump_all_keys_or_addrs(wallet_obj=wallet_obj)
485450
function (uuids) {
    var walletJSON = {
      guid: uuids.guid,
      sharedKey: uuids.sharedKey,
      double_encryption: false,
      options: {
        pbkdf2_iterations: 5000,
        html5_notifications: false,
        fee_per_kb: 10000,
        logout_time: 600000
      }
    }

    var createHdWallet = function (label) {
      label = label == null ? 'My Bitcoin Wallet' : label
      var mnemonic = BIP39.generateMnemonic(undefined, Blockchain.RNG.run.bind(Blockchain.RNG))
      var hd = HDWallet.new(mnemonic)
      hd.newAccount(label)
      return hd
    }

    var createLegacyAddress = function (priv, label) {
      return priv ? Address.import(priv, label) : Address.new(label)
    }

    if (isHdWallet) {
      var hdJSON = createHdWallet(firstLabel).toJSON()
      hdJSON.accounts = hdJSON.accounts.map(function (a) { return a.toJSON() })
      walletJSON.hd_wallets = [hdJSON]
    } else {
      winston.warn(warnings.CREATED_NON_HD)
      var firstAddress = createLegacyAddress(privateKey, firstLabel)
      walletJSON.keys = [firstAddress.toJSON()]
    }

    if (typeof secPass === 'string' && secPass.length) {
      walletJSON = JSON.parse(JSON.stringify(new Wallet(walletJSON).encrypt(secPass)))
    }

    return walletJSON
  }
1259909
function WalletKey(options, network) {
  if (!(this instanceof WalletKey))
    return new WalletKey(options, network);

  KeyRing.call(this, options, network);

  this.keyType = Path.types.HD;

  this.id = null;
  this.wid = -1;
  this.name = null;
  this.account = -1;
  this.branch = -1;
  this.index = -1;
}
285726
def _make_pkh_address(pubkey_hash, witness=False, cashaddr=True):
    '''
    
    '''
    addr_bytes = bytearray()
    if riemann.network.CASHADDR_P2PKH is not None and cashaddr:
        addr_bytes.extend(riemann.network.CASHADDR_P2PKH)
        addr_bytes.extend(pubkey_hash)
        return riemann.network.CASHADDR_ENCODER.encode(addr_bytes)
    if witness:
        addr_bytes.extend(riemann.network.P2WPKH_PREFIX)
        addr_bytes.extend(pubkey_hash)
        return riemann.network.SEGWIT_ENCODER.encode(addr_bytes)
    else:
        addr_bytes.extend(riemann.network.P2PKH_PREFIX)
        addr_bytes.extend(pubkey_hash)
        return riemann.network.LEGACY_ENCODER.encode(addr_bytes)
282860
async def remove(self, von_wallet: Wallet) -> None:
        

        LOGGER.debug('WalletManager.remove >>> wallet %s', von_wallet)

        await von_wallet.remove()

        LOGGER.debug('WalletManager.remove <<<')