called from network, without user interaction One of the proposed cosigners declined wallet creation
496777
function deleteWallet(wallet, rejector_device_address, onDone){
	db.query("SELECT approval_date FROM extended_pubkeys WHERE wallet=? AND device_address=?", [wallet, rejector_device_address], function(rows){
		if (rows.length === 0) // you are not a member device
			return onDone();
		if (rows[0].approval_date) // you've already approved this wallet, you can't change your mind
			return onDone();
		db.query("SELECT device_address FROM extended_pubkeys WHERE wallet=?", [wallet], function(rows){
			var arrMemberAddresses = rows.map(function(row){ return row.device_address; });
			var arrQueries = [];
			db.addQuery(arrQueries, "DELETE FROM extended_pubkeys WHERE wallet=?", [wallet]);
			db.addQuery(arrQueries, "DELETE FROM wallet_signing_paths WHERE wallet=?", [wallet]);
			db.addQuery(arrQueries, "DELETE FROM wallets WHERE wallet=?", [wallet]);
			// delete unused indirect correspondents
			db.addQuery(
				arrQueries, 
				"DELETE FROM correspondent_devices WHERE is_indirect=1 AND device_address IN(?) AND NOT EXISTS ( \n\
					SELECT * FROM extended_pubkeys WHERE extended_pubkeys.device_address=correspondent_devices.device_address \n\
				)", 
				[arrMemberAddresses]
			);
			async.series(arrQueries, function(){
				eventBus.emit('wallet_declined', wallet, rejector_device_address);
				onDone();
			});
		});
	});
}
1093530
async def open(self) -> 'Wallet':
        

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

        if not self.created:
            LOGGER.debug('Wallet.open: <!< absent wallet %s', self.name)
            raise AbsentWallet('Cannot open wallet {}: not created'.format(self.name))

        self._handle = await wallet.open_wallet(
            json.dumps(self.cfg),
            json.dumps(self.access_creds))
        LOGGER.info('Opened wallet %s on handle %s', self.name, self.handle)

        self._did = await self._seed2did()
        self._verkey = await did.key_for_local_did(self.handle, self.did)
        LOGGER.info('Wallet %s got verkey %s for existing DID %s', self.name, self.verkey, self.did)

        LOGGER.debug('Wallet.open <<<')
        return self
278287
public AbucoinsCreateOrderResponse createAbucoinsOrder(AbucoinsBaseCreateOrderRequest req)
      throws IOException {
    AbucoinsCreateOrderResponse resp =
        abucoinsAuthenticated.createOrder(
            exchange.getExchangeSpecification().getApiKey(),
            signatureCreator,
            exchange.getExchangeSpecification().getPassword(),
            timestamp(),
            req);
    if (resp.getMessage() != null) throw new ExchangeException(resp.getMessage());

    return resp;
  }
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;
}
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();
    }
451711
function checkStability() {
		db.query(
			"SELECT is_stable, asset, SUM(amount) AS `amount` \n\
			FROM outputs JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_spent=0 GROUP BY asset ORDER BY asset DESC LIMIT 1", 
			[addrInfo.address],
			function(rows){
				if (rows.length === 0) {
					cb("This textcoin either was already claimed or never existed in the network");
				} else {
					var row = rows[0];
					if (false && !row.is_stable) {
						cb("This payment is not confirmed yet, try again later");
					} else {
						if (row.asset) { // claiming asset
							opts.asset = row.asset;
							opts.amount = row.amount;
							opts.fee_paying_addresses = [addrInfo.address];
							storage.readAsset(db, row.asset, null, function(err, objAsset){
								if (err && err.indexOf("not found" !== -1)) {
									if (!conf.bLight) // full wallets must have this asset
										throw Error("textcoin asset "+row.asset+" not found");
									return network.requestHistoryFor([opts.asset], [], checkStability);
								}
								asset = opts.asset;
								opts.to_address = addressTo;
								if (objAsset.fixed_denominations){ // indivisible
									opts.tolerance_plus = 0;
									opts.tolerance_minus = 0;
									indivisibleAsset.composeAndSaveIndivisibleAssetPaymentJoint(opts);
								}
								else{ // divisible
									divisibleAsset.composeAndSaveDivisibleAssetPaymentJoint(opts);
								}
							});
						} else {// claiming bytes
							opts.send_all = true;
							opts.outputs = [{address: addressTo, amount: 0}];
							opts.callbacks = composer.getSavingCallbacks(opts.callbacks);
							composer.composeJoint(opts);
						}
					}
				}
			}
		);		
	}
1185370
function readSingleWallet(conn, handleWallet){
	conn.query("SELECT wallet FROM wallets", function(rows){
		if (rows.length === 0)
			throw Error("no wallets");
		if (rows.length > 1)
			throw Error("more than 1 wallet");
		handleWallet(rows[0].wallet);
	});
}
44899
function WalletClient(options) {
  if (!(this instanceof WalletClient))
    return new WalletClient(options);

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { uri: options };

  AsyncObject.call(this);

  this.options = options;
  this.network = Network.get(options.network);

  this.uri = options.uri || `http://localhost:${this.network.rpcPort}`;
  this.apiKey = options.apiKey;

  this.socket = null;
}
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);
			});
		});
	});
}
925551
function createWallet (password, options) {
  if (!password || password.length > 255) {
    return Promise.reject('Password must exist and be shorter than 256 characters')
  }

  options = options || {}
  var email = options.email
  var firstLabel = options.firstLabel
  var privateKey = options.privateKey
  var secPass = options.secondPassword
  var isHdWallet = Boolean(options.hd)

  Blockchain.API.API_CODE = options.api_code

  // Handle response from WalletNetwork
  var generatedUUIDs = function (uuids) {
    var guid = uuids[0]
    var sharedKey = uuids[1]

    if (!guid || !sharedKey || guid.length !== 36 || sharedKey.length !== 36) {
      throw 'Error generating wallet identifier'
    }

    return { guid: guid, sharedKey: sharedKey }
  }

  // Generate new Wallet JSON, add first key
  var newWallet = 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
  }

  // Encrypt and push new wallet to server
  var insertWallet = function (wallet) {
    var data = JSON.stringify(wallet, null, 2)
    var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0)
    var check = sha256(enc).toString('hex')

    // Throws if there is an encryption error
    Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () {
      throw 'Failed to confirm successful encryption when generating new wallet'
    })

    var postData = {
      guid: wallet.guid,
      sharedKey: wallet.sharedKey,
      length: enc.length,
      payload: enc,
      checksum: check,
      method: 'insert',
      format: 'plain'
    }

    if (email) postData.email = email

    return Blockchain.API.securePost('wallet', postData).then(function () {
      if (isHdWallet) {
        var account = wallet.hd_wallets[0].accounts[0]
        return { guid: wallet.guid, address: account.xpub, label: account.label }
      } else {
        var firstKey = wallet.keys[0]
        return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD }
      }
    })
  }

  return WalletNetwork.generateUUIDs(2)
    .then(generatedUUIDs)
    .then(newWallet)
    .then(insertWallet)
    .catch(function (err) { throw err === 'Unknown API Key' ? 'ERR_API_KEY' : err })
}
263851
def user
      response = JSON.parse(@client.get("wallet_accounts/#{send(:id)}/users").body)
      response.key?('users') ? Promisepay::User.new(@client, response['users']) : nil
    end
363719
def walletpassphrase(self, passphrase, timeout=99999999, mint_only=True):
        """"""
        return self.req("walletpassphrase", [passphrase, timeout, mint_only])
74931
public void task_contactChange_id_refuse_POST(Long id, String token) throws IOException {
		String qPath = "/me/task/contactChange/{id}/refuse";
		StringBuilder sb = path(qPath, id);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "token", token);
		exec(qPath, "POST", sb.toString(), o);
	}
491528
def delete_wallet(self, wallet_name):
        
        return make_request(
            '{}wallet/{}'.format(self.url, wallet_name),
            method='DELETE',
            timeout=self.timeout,
            client=self._client)
1054335
public void newTransactionHandler(PersistedTransaction tx, PersistedV2Key key) throws Exception {
        listenForUpdates(tx);
        tx.keyId = key.getId();
        tx.walletId = this.descriptor.getKey();
        tx.account = key.account;
        System.out.println("Incoming transaction captured in API service: " + tx.toString());
        transactionDAO.create(tx);
        WalletChange change = new WalletChange(tx.value, getBalance(), createKey(key.account).address, tx);
        WalletChangeMessage out = new WalletChangeMessage();
        out.setCommand(Command.BALANCE_CHANGE_RECEIVED);
        out.setKey(this.descriptor.key);
        out.setPayload(change);
        router.sendUpdate(this.descriptor.key, out);
    }
596024
def disapproveproposal(self, proposal_ids, account=None, approver=None, **kwargs):
        
        from .proposal import Proposal

        if not account:
            if "default_account" in self.config:
                account = self.config["default_account"]
        if not account:
            raise ValueError("You need to provide an account")
        account = Account(account, blockchain_instance=self)
        if not approver:
            approver = account
        else:
            approver = Account(approver, blockchain_instance=self)

        if not isinstance(proposal_ids, (list, set, tuple)):
            proposal_ids = {proposal_ids}

        op = []
        for proposal_id in proposal_ids:
            proposal = Proposal(proposal_id, blockchain_instance=self)
            op.append(
                operations.Proposal_update(
                    **{
                        "fee": {"amount": 0, "asset_id": "1.3.0"},
                        "fee_paying_account": account["id"],
                        "proposal": proposal["id"],
                        "active_approvals_to_remove": [approver["id"]],
                        "prefix": self.prefix,
                    }
                )
            )
        return self.finalizeOp(op, account["name"], "active", **kwargs)
925183
def subscribe_to_wallet_webhook(callback_url, wallet_name,
        event='tx-confirmation', coin_symbol='btc', api_key=None):
    '''
    
    '''
    assert is_valid_coin_symbol(coin_symbol)
    assert is_valid_wallet_name(wallet_name), wallet_name
    assert api_key, 'api_key required'

    url = make_url(coin_symbol, 'hooks')

    params = {'token': api_key}
    data = {
        'event': event,
        'url': callback_url,
        'wallet_name': wallet_name,
    }

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    response_dict = get_valid_json(r)
    return response_dict['id']