Receives public key, looking up document at storage,
				sends document id to the balance server
356365
async def get(self, public_key):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		response = await self.account.getnews(public_key=public_key)
		# If we`ve got a empty or list with news 
		if isinstance(response, list):
			self.write(json.dumps(response))
			raise tornado.web.Finish
		# If we`ve got a message with error
		elif isinstance(response, dict):
			try:
				error_code = response["error"]
			except:
				del response["account_id"]

				self.write(response)
			else:
				self.set_status(error_code)
				self.write(response)
				raise tornado.web.Finish
796630
def public_key_to_connection_id(self, public_key):
        
        with self._connections_lock:
            for connection_id, connection_info in self._connections.items():
                if connection_info.public_key == public_key:
                    return connection_id

            return None
529013
function parseArgs (f) {
  return function (args, opts, callback) {
    var credentials = auth(opts.req)
    var guid = credentials.name
    var walletOpts = { password: credentials.pass, apiCode: apiCode }

    if (!guid) throw 'Missing wallet guid'
    if (!walletOpts.password) throw 'Missing wallet password'

    if (args.length > f.$params.length) {
      throw 'Expected max of ' + f.$params.length + ' parameters, received ' + args.length
    }

    var params = f.$params
      .map(function (param, i) {
        return {
          name: param.split('?')[0],
          value: args[i],
          required: !~param.indexOf('?')
        }
      })
      .reduce(function (acc, param) {
        if (param.value == null && param.required) throw 'Missing parameter: ' + param.name
        acc[param.name] = param.value
        return acc
      }, {})

    var action = f.$nowallet
      ? Promise.resolve(f(params))
      : api.getWallet(guid, walletOpts).then(f.bind(f, params))

    action
      .then(callback.bind(null, null))
      .catch(callback)
  }
}
515581
def send(self, wallet_id, passcode, address, amount, message='', fee=None, fan_unspend=10):
        
        MINIMAL_FEE = 20000
        MINIMAL_SPLIT = 10000000

        wallet = self.get_wallet(wallet_id)

        if not wallet['spendingAccount']:
            raise NotSpendableWallet()

        if not wallet['isActive']:
            raise NotActiveWallet()

        if amount < 10000:
            raise Exception('amount to small')

        if wallet['confirmedBalance'] < amount:
            raise NotEnoughFunds('Not enough funds: balance %s amount %s' %
                                 (wallet['confirmedBalance'], amount)
            )

        change_address = self.create_address(wallet_id, chain=1)
        usableKeychain = False
        spendables = []
        chain_paths = []
        p2sh = []
        payables = [(address, amount)]
        keychain_path = ""

        for keychain in wallet['private']['keychains']:
            keychain_path = keychain['path'][1:]
            keychain = self.get_keychain(keychain['xpub'])
            if 'encryptedXprv' not in keychain:
                continue
            usableKeychain = True
            break

        if not usableKeychain:
            raise BitGoError("didn't found a spendable keychain")

        data = json.loads(keychain['encryptedXprv'])
        #add base64 paddings
        for k in ['iv', 'salt', 'ct']:
            data[k] = data[k] + "=="
        cipher = sjcl.SJCL()
        xprv = cipher.decrypt(data, passcode)

        unspents = self.get_unspents(wallet_id)
        unspents = filter(lambda u: u['confirmations'] > 0, unspents['unspents'][::-1])

        total_value = 0
        for d in unspents:
            path = keychain_path + d['chainPath']
            chain_paths.append(path)
            p2sh.append(h2b(d["redeemScript"]))
            spendables.append(Spendable(d["value"],
                                  h2b(d["script"]),
                                  h2b_rev(d["tx_hash"]),
                                  d["tx_output_n"]))

            total_value += d['value']
            if total_value > amount:
                break

        # make many outputs?
        if len(unspents) < 5 and (total_value > (amount + MINIMAL_SPLIT)) and fan_unspend > 0:
            fee = self.calculate_fee(len(spendables), fan_unspend)
            value = (total_value - amount - fee) / fan_unspend
            for i in range(fan_unspend):
                payables.append((change_address, value))
        elif total_value > (amount + MINIMAL_FEE):
            # add a change address
            if fee is None:
                fee = self.calculate_fee(len(spendables), 2)
            value = total_value - amount - fee
            if value > 10000: #avoid dust
                payables.append((change_address, value))

        p2sh_lookup = build_p2sh_lookup(p2sh)

        spendable_keys = []

        priv_key = BIP32Node.from_hwif(xprv)

        spendable_keys = [priv_key.subkey_for_path(path) for path in chain_paths]

        hash160_lookup = build_hash160_lookup([key.secret_exponent() for key in spendable_keys])

        tx = create_tx(spendables, payables)

        tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)

        r = requests.post(self.url + '/tx/send', {
                'tx': tx.as_hex(),
                'message': message
            }, headers={
                'Authorization': 'Bearer %s' % self.access_token,
            })

        return r.json()
1046497
def load_public_key(vm_):
    '''
    
    '''
    public_key_filename = config.get_cloud_config_value(
        'ssh_public_key', vm_, __opts__, search_global=False, default=None
    )
    if public_key_filename is not None:
        public_key_filename = os.path.expanduser(public_key_filename)
        if not os.path.isfile(public_key_filename):
            raise SaltCloudConfigError(
                'The defined ssh_public_key \'{0}\' does not exist'.format(
                    public_key_filename
                )
            )

        with salt.utils.files.fopen(public_key_filename, 'r') as public_key:
            key = salt.utils.stringutils.to_unicode(public_key.read().replace('\n', ''))

            return key
1028167
def load(self, record_key, secret_key=''):

        ''' 
            
        '''

        title = '%s.load' % self.__class__.__name__
    
    # validate inputs
        input_fields = {
            'record_key': record_key,
            'secret_key': secret_key
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)

    # verify permissions
        if not self.permissions_content:
            raise Exception('%s requires an access_token with file content permissions.' % title)
            
    # retrieve file id
        file_id, parent_id = self._get_id(record_key)
        if not file_id:
            raise Exception('%s(record_key=%s) does not exist.' % (title, record_key))
    
    # request file data
        try:
            record_data = self.drive.get_media(fileId=file_id).execute()
        except:
            raise DriveConnectionError(title)
    
    # retrieve data from response
    #     import io
    #     from googleapiclient.http import MediaIoBaseDownload
    #     file_header = io.BytesIO
    #     record_data = MediaIoBaseDownload(file_header, response)
    #     done = False
    #     while not done:
    #         status, done = record_data.next_chunk()
    
    # TODO export google document to other format
            
    # decrypt (if necessary)
        if secret_key:
            from labpack.encryption import cryptolab
            record_data = cryptolab.decrypt(record_data, secret_key)
    
        return record_data
364525
async def get(self, public_key):
		
		# Sign-verifying functional
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		logging.debug("\n\n --  Input offers debugging")

		message = json.loads(self.get_argument("message"))
		cid = message.get("cid")
		coinid = message.get("coinid")
		if not cid:
			self.set_status(400)
			self.write({"error":400, "reason":"Missed required fields."})
			raise tornado.web.Finish


		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			self.set_status(account["error"])
			self.write(account)
			raise tornado.web.Finish

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		offers = await self.account.blockchain.getcidoffers(cid=cid)
		logging.debug("\n\n -- Offers")
		logging.debug(offers)

		if isinstance(offers, dict):
			self.set_status(offers["error"])
			self.write(offers)
			raise tornado.web.Finish

		for offer in offers:
			offer["type"] = self.account.ident_offer[offer["type"]]

		storage_offers = await self.account.getoffers(cid=cid, coinid=coinid)
		logging.debug("\n\n -- Storage offers. ")
		logging.debug(storage_offers)

		self.write(json.dumps(offers + storage_offers))
514177
def _deposit_payload(to_deposit):
    
    pubsub = to_deposit['pubsub']
    id = to_deposit['id']

    with r_client.pipeline() as pipe:
        pipe.set(id, json.dumps(to_deposit), ex=REDIS_KEY_TIMEOUT)
        pipe.publish(pubsub, json.dumps({"update": [id]}))
        pipe.execute()
407217
def get_common_secret(self, server_public, client_public):
        
        return self.hash(self.pad(client_public), self.pad(server_public))
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})
816513
function() {
      var ids = [];
      // search localstorage for saved documents
      for ( var i = 0, max = localStorage.length; i < max; i++) {
        var key = localStorage.key(i);
        // value is a document if key confirms to prefix
        if (key.indexOf(prefix) == 0) {
          ids.push(key.substring(prefix.length));
        }
      }
      return ids;
    }
658652
def hashdata(self, subject):
        _data = bytearray()

        if isinstance(subject, six.string_types):
            subject = subject.encode('charmap')

        

        if self.type == SignatureType.BinaryDocument:
            """
            For binary document signatures (type 0x00), the document data is
            hashed directly.
            """
            if isinstance(subject, (SKEData, IntegrityProtectedSKEData)):
                _data += subject.__bytearray__()
            else:
                _data += bytearray(subject)

        if self.type == SignatureType.CanonicalDocument:
            """
            For text document signatures (type 0x01), the
            document is canonicalized by converting line endings to <CR><LF>,
            and the resulting data is hashed.
            """
            _data += re.subn(br'\r?\n', b'\r\n', subject)[0]

        if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
                         SignatureType.Positive_Cert, SignatureType.CertRevocation, SignatureType.Subkey_Binding,
                         SignatureType.PrimaryKey_Binding}:
            """
            When a signature is made over a key, the hash data starts with the
            octet 0x99, followed by a two-octet length of the key, and then body
            of the key packet.  (Note that this is an old-style packet header for
            a key packet with two-octet length.) ...
            Key revocation signatures (types 0x20 and 0x28)
            hash only the key being revoked.
            """
            _s = b''
            if isinstance(subject, PGPUID):
                _s = subject._parent.hashdata

            elif isinstance(subject, PGPKey) and not subject.is_primary:
                _s = subject._parent.hashdata

            elif isinstance(subject, PGPKey) and subject.is_primary:
                _s = subject.hashdata

            if len(_s) > 0:
                _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

        if self.type in {SignatureType.Subkey_Binding, SignatureType.PrimaryKey_Binding}:
            """
            A subkey binding signature
            (type 0x18) or primary key binding signature (type 0x19) then hashes
            the subkey using the same format as the main key (also using 0x99 as
            the first octet).
            """
            if subject.is_primary:
                _s = subject.subkeys[self.signer].hashdata

            else:
                _s = subject.hashdata

            _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

        if self.type in {SignatureType.KeyRevocation, SignatureType.SubkeyRevocation, SignatureType.DirectlyOnKey}:
            """
            The signature is calculated directly on the key being revoked.  A
            revoked key is not to be used.  Only revocation signatures by the
            key being revoked, or by an authorized revocation key, should be
            considered valid revocation signatures.

            Subkey revocation signature
            The signature is calculated directly on the subkey being revoked.
            A revoked subkey is not to be used.  Only revocation signatures
            by the top-level signature key that is bound to this subkey, or
            by an authorized revocation key, should be considered valid
            revocation signatures.
            
            - clarification from draft-ietf-openpgp-rfc4880bis-02:
            Primary key revocation signatures (type 0x20) hash
            only the key being revoked.  Subkey revocation signature (type 0x28)
            hash first the primary key and then the subkey being revoked

            Signature directly on a key
            This signature is calculated directly on a key.  It binds the
            information in the Signature subpackets to the key, and is
            appropriate to be used for subpackets that provide information
            about the key, such as the Revocation Key subpacket.  It is also
            appropriate for statements that non-self certifiers want to make
            about the key itself, rather than the binding between a key and a
            name.
            """
            if self.type == SignatureType.SubkeyRevocation:
                # hash the primary key first if this is a Subkey Revocation signature
                _s = subject.parent.hashdata
                _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

            _s = subject.hashdata
            _data += b'\x99' + self.int_to_bytes(len(_s), 2) + _s

        if self.type in {SignatureType.Generic_Cert, SignatureType.Persona_Cert, SignatureType.Casual_Cert,
                         SignatureType.Positive_Cert, SignatureType.CertRevocation}:
            """
            A certification signature (type 0x10 through 0x13) hashes the User
            ID being bound to the key into the hash context after the above
            data.  ...  A V4 certification
            hashes the constant 0xB4 for User ID certifications or the constant
            0xD1 for User Attribute certifications, followed by a four-octet
            number giving the length of the User ID or User Attribute data, and
            then the User ID or User Attribute data.

            ...

            The [certificate revocation] signature
            is computed over the same data as the certificate that it
            revokes, and should have a later creation date than that
            certificate.
            """

            _s = subject.hashdata
            if subject.is_uid:
                _data += b'\xb4'

            else:
                _data += b'\xd1'

            _data += self.int_to_bytes(len(_s), 4) + _s

        # if this is a new signature, do update_hlen
        if 0 in list(self._signature.signature):
            self._signature.update_hlen()

        """
        Once the data body is hashed, then a trailer is hashed. (...)
        A V4 signature hashes the packet body
        starting from its first field, the version number, through the end
        of the hashed subpacket data.  Thus, the fields hashed are the
        signature version, the signature type, the public-key algorithm, the
        hash algorithm, the hashed subpacket length, and the hashed
        subpacket body.

        V4 signatures also hash in a final trailer of six octets: the
        version of the Signature packet, i.e., 0x04; 0xFF; and a four-octet,
        big-endian number that is the length of the hashed data from the
        Signature packet (note that this number does not include these final
        six octets).
        """

        hcontext = bytearray()
        hcontext.append(self._signature.header.version if not self.embedded else self._signature._sig.header.version)
        hcontext.append(self.type)
        hcontext.append(self.key_algorithm)
        hcontext.append(self.hash_algorithm)
        hcontext += self._signature.subpackets.__hashbytearray__()
        hlen = len(hcontext)
        _data += hcontext
        _data += b'\x04\xff'
        _data += self.int_to_bytes(hlen, 4)
        return bytes(_data)
835257
private static boolean keyIsValid(final BinaryRequest request) {
        if (request.keyBytes() == null || request.keyBytes().length < MIN_KEY_BYTES) {
            request.observable().onError(new IllegalArgumentException("The Document ID must not be null or empty."));
            return false;
        }

        if (request.keyBytes().length > MAX_KEY_BYTES) {
            request.observable().onError(new IllegalArgumentException(
                "The Document ID must not be longer than 250 bytes."));
            return false;
        }

        return true;
    }
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
  }
1255351
def doc_id(self):
        
        if self.id:
            return '%s_%s' % (self.doc_type, self.id.lower())
        return self._hashed_key
675042
def get_transaction_document(current_block: dict, source: dict, from_pubkey: str, to_pubkey: str) -> Transaction:
    
    # list of inputs (sources)
    inputs = [
        InputSource(
            amount=source['amount'],
            base=source['base'],
            source=source['type'],
            origin_id=source['identifier'],
            index=source['noffset']
        )
    ]

    # list of issuers of the inputs
    issuers = [
        from_pubkey
    ]

    # list of unlocks of the inputs
    unlocks = [
        Unlock(
            # inputs[index]
            index=0,
            # unlock inputs[index] if signatures[0] is from public key of issuers[0]
            parameters=[SIGParameter(0)]
        )
    ]

    # lists of outputs
    outputs = [
        OutputSource(amount=source['amount'], base=source['base'], condition="SIG({0})".format(to_pubkey))
    ]

    transaction = Transaction(
        version=TRANSACTION_VERSION,
        currency=current_block['currency'],
        blockstamp=BlockUID(current_block['number'], current_block['hash']),
        locktime=0,
        issuers=issuers,
        inputs=inputs,
        unlocks=unlocks,
        outputs=outputs,
        comment='',
        signatures=[]
    )

    return transaction
790054
def post_public_key(self, path, data, is_json=True):
        ''''''
        post_data = {
            'public_key': self.public_key
        }
        post_data.update(data)
        return self._post(path, post_data, is_json)