INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Create a :class:`Transaction` object from a Transaction XDR
object.
|
def from_xdr_object(cls, tx_xdr_object):
"""Create a :class:`Transaction` object from a Transaction XDR
object.
"""
source = encode_check('account', tx_xdr_object.sourceAccount.ed25519)
sequence = tx_xdr_object.seqNum - 1
time_bounds_in_xdr = tx_xdr_object.timeBounds # TODO test
if time_bounds_in_xdr:
time_bounds = {
'maxTime': time_bounds_in_xdr[0].maxTime,
'minTime': time_bounds_in_xdr[0].minTime
}
else:
time_bounds = None
memo = xdr_to_memo(tx_xdr_object.memo)
operations = list(map(
Operation.from_xdr_object, tx_xdr_object.operations
))
return cls(
source=source,
sequence=sequence,
time_bounds=time_bounds,
memo=memo,
fee=tx_xdr_object.fee,
operations=operations)
|
Generate a :class:`Keypair` object via a deterministic
phrase.
Using a mnemonic, such as one generated from :class:`StellarMnemonic`,
generate a new keypair deterministically. Uses :class:`StellarMnemonic`
internally to generate the seed from the mnemonic, using PBKDF2.
:param str mnemonic: A unique string used to deterministically generate
keypairs.
:param str passphrase: An optional passphrase used as part of the salt
during PBKDF2 rounds when generating the seed from the mnemonic.
:param str lang: The language of the mnemonic, defaults to english.
:param int index: The index of the keypair generated by the mnemonic.
This allows for multiple Keypairs to be derived from the same
mnemonic, such as::
>>> from stellar_base.keypair import Keypair
>>> m = 'update hello cry airport drive chunk elite boat shaft sea describe number' # Don't use this mnemonic in practice.
>>> kp1 = Keypair.deterministic(m, lang='english', index=0)
>>> kp2 = Keypair.deterministic(m, lang='english', index=1)
>>> kp3 = Keypair.deterministic(m, lang='english', index=2)
:return: A new :class:`Keypair` instance derived from the mnemonic.
|
def deterministic(cls, mnemonic, passphrase='', lang='english', index=0):
"""Generate a :class:`Keypair` object via a deterministic
phrase.
Using a mnemonic, such as one generated from :class:`StellarMnemonic`,
generate a new keypair deterministically. Uses :class:`StellarMnemonic`
internally to generate the seed from the mnemonic, using PBKDF2.
:param str mnemonic: A unique string used to deterministically generate
keypairs.
:param str passphrase: An optional passphrase used as part of the salt
during PBKDF2 rounds when generating the seed from the mnemonic.
:param str lang: The language of the mnemonic, defaults to english.
:param int index: The index of the keypair generated by the mnemonic.
This allows for multiple Keypairs to be derived from the same
mnemonic, such as::
>>> from stellar_base.keypair import Keypair
>>> m = 'update hello cry airport drive chunk elite boat shaft sea describe number' # Don't use this mnemonic in practice.
>>> kp1 = Keypair.deterministic(m, lang='english', index=0)
>>> kp2 = Keypair.deterministic(m, lang='english', index=1)
>>> kp3 = Keypair.deterministic(m, lang='english', index=2)
:return: A new :class:`Keypair` instance derived from the mnemonic.
"""
sm = StellarMnemonic(lang)
seed = sm.to_seed(mnemonic, passphrase=passphrase, index=index)
return cls.from_raw_seed(seed)
|
Generate a :class:`Keypair` object via a sequence of bytes.
Typically these bytes are random, such as the usage of
:func:`os.urandom` in :meth:`Keypair.random`. However this class method
allows you to use an arbitrary sequence of bytes, provided the sequence
is 32 bytes long.
:param bytes raw_seed: A bytes object used as the seed for generating
the keypair.
:return: A new :class:`Keypair` derived by the raw secret seed.
|
def from_raw_seed(cls, raw_seed):
"""Generate a :class:`Keypair` object via a sequence of bytes.
Typically these bytes are random, such as the usage of
:func:`os.urandom` in :meth:`Keypair.random`. However this class method
allows you to use an arbitrary sequence of bytes, provided the sequence
is 32 bytes long.
:param bytes raw_seed: A bytes object used as the seed for generating
the keypair.
:return: A new :class:`Keypair` derived by the raw secret seed.
"""
signing_key = ed25519.SigningKey(raw_seed)
verifying_key = signing_key.get_verifying_key()
return cls(verifying_key, signing_key)
|
Generate a :class:`Keypair` object via Base58 encoded seed.
.. deprecated:: 0.1.7
Base58 address encoding is DEPRECATED! Use this method only for
transition to strkey encoding.
:param str base58_seed: A base58 encoded encoded secret seed.
:return: A new :class:`Keypair` derived from the secret seed.
|
def from_base58_seed(cls, base58_seed):
"""Generate a :class:`Keypair` object via Base58 encoded seed.
.. deprecated:: 0.1.7
Base58 address encoding is DEPRECATED! Use this method only for
transition to strkey encoding.
:param str base58_seed: A base58 encoded encoded secret seed.
:return: A new :class:`Keypair` derived from the secret seed.
"""
warnings.warn(
"Base58 address encoding is DEPRECATED! Use this method only for "
"transition to strkey encoding.", DeprecationWarning)
raw_seed = b58decode_check(base58_seed)[1:]
return cls.from_raw_seed(raw_seed)
|
Generate a :class:`Keypair` object via a strkey encoded public key.
:param str address: A base32 encoded public key encoded as described in
:func:`encode_check`
:return: A new :class:`Keypair` with only a verifying (public) key.
|
def from_address(cls, address):
"""Generate a :class:`Keypair` object via a strkey encoded public key.
:param str address: A base32 encoded public key encoded as described in
:func:`encode_check`
:return: A new :class:`Keypair` with only a verifying (public) key.
"""
public_key = is_valid_address(address)
verifying_key = ed25519.VerifyingKey(public_key)
return cls(verifying_key)
|
Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type.
|
def account_xdr_object(self):
"""Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type.
"""
return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519,
self.verifying_key.to_bytes())
|
Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
|
def xdr(self):
"""Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
"""
kp = Xdr.StellarXDRPacker()
kp.pack_PublicKey(self.account_xdr_object())
return base64.b64encode(kp.get_buffer())
|
Sign a bytes-like object using the signing (private) key.
:param bytes data: The data to sign
:return: The signed data
:rtype: bytes
|
def sign(self, data):
"""Sign a bytes-like object using the signing (private) key.
:param bytes data: The data to sign
:return: The signed data
:rtype: bytes
"""
if self.signing_key is None:
raise MissingSigningKeyError("KeyPair does not contain secret key. "
"Use Keypair.from_seed method to create a new keypair with a secret key.")
return self.signing_key.sign(data)
|
Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that were previously signed by
the private key associated with this verifying key.
:param bytes signature: A sequence of bytes that comprised the
signature for the corresponding data.
|
def verify(self, data, signature):
"""Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that were previously signed by
the private key associated with this verifying key.
:param bytes signature: A sequence of bytes that comprised the
signature for the corresponding data.
"""
try:
return self.verifying_key.verify(signature, data)
except ed25519.BadSignatureError:
raise BadSignatureError("Signature verification failed.")
|
Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go along with
the signature as an XDR DecoratedSignature object.
:param bytes data: A sequence of bytes to sign, typically a
transaction.
|
def sign_decorated(self, data):
"""Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go along with
the signature as an XDR DecoratedSignature object.
:param bytes data: A sequence of bytes to sign, typically a
transaction.
"""
signature = self.sign(data)
hint = self.signature_hint()
return Xdr.types.DecoratedSignature(hint, signature)
|
Creates an XDR Operation object that represents this
:class:`Operation`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`Operation`.
"""
try:
source_account = [account_xdr_object(self.source)]
except StellarAddressInvalidError:
source_account = []
return Xdr.types.Operation(source_account, self.body)
|
copy from base64._bytes_from_decode_data
|
def bytes_from_decode_data(s):
"""copy from base64._bytes_from_decode_data
"""
if isinstance(s, (str, unicode)):
try:
return s.encode('ascii')
except UnicodeEncodeError:
raise NotValidParamError(
'String argument should contain only ASCII characters')
if isinstance(s, bytes_types):
return s
try:
return memoryview(s).tobytes()
except TypeError:
raise suppress_context(
TypeError(
'Argument should be a bytes-like object or ASCII string, not '
'{!r}'.format(s.__class__.__name__)))
|
Packs and base64 encodes this :class:`Operation` as an XDR string.
|
def xdr(self):
"""Packs and base64 encodes this :class:`Operation` as an XDR string.
"""
op = Xdr.StellarXDRPacker()
op.pack_Operation(self.to_xdr_object())
return base64.b64encode(op.get_buffer())
|
Converts an amount to the appropriate value to send over the network
as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR
structures. An asset amount unit (that which is seen by end users) is
scaled down by a factor of ten million (10,000,000) to arrive at the
native 64-bit integer representation. For example, the integer amount
value 25,123,456 equals 2.5123456 units of the asset. This scaling
allows for seven decimal places of precision in human-friendly amount
units.
This static method correctly multiplies the value by the scaling factor
in order to come to the integer value used in XDR structures.
See `Stellar's documentation on Asset Precision
<https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_
for more information.
:param str value: The amount to convert to an integer for XDR
serialization.
|
def to_xdr_amount(value):
"""Converts an amount to the appropriate value to send over the network
as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR
structures. An asset amount unit (that which is seen by end users) is
scaled down by a factor of ten million (10,000,000) to arrive at the
native 64-bit integer representation. For example, the integer amount
value 25,123,456 equals 2.5123456 units of the asset. This scaling
allows for seven decimal places of precision in human-friendly amount
units.
This static method correctly multiplies the value by the scaling factor
in order to come to the integer value used in XDR structures.
See `Stellar's documentation on Asset Precision
<https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_
for more information.
:param str value: The amount to convert to an integer for XDR
serialization.
"""
if not isinstance(value, str):
raise NotValidParamError("Value of type '{}' must be of type String, but got {}".format(value, type(value)))
# throw exception if value * ONE has decimal places (it can't be
# represented as int64)
try:
amount = int((Decimal(value) * ONE).to_integral_exact(context=Context(traps=[Inexact])))
except decimal.Inexact:
raise NotValidParamError("Value of '{}' must have at most 7 digits after the decimal.".format(value))
except decimal.InvalidOperation:
raise NotValidParamError("Value of '{}' must represent a positive number.".format(value))
return amount
|
Create the appropriate :class:`Operation` subclass from the XDR
structure.
Decode an XDR base64 encoded string and create the appropriate
:class:`Operation` object.
:param str xdr: The XDR object to create an :class:`Operation` (or
subclass) instance from.
|
def from_xdr(cls, xdr):
"""Create the appropriate :class:`Operation` subclass from the XDR
structure.
Decode an XDR base64 encoded string and create the appropriate
:class:`Operation` object.
:param str xdr: The XDR object to create an :class:`Operation` (or
subclass) instance from.
"""
xdr_decode = base64.b64decode(xdr)
op = Xdr.StellarXDRUnpacker(xdr_decode)
op = op.unpack_Operation()
return cls.from_xdr_object(op)
|
Creates an XDR Operation object that represents this
:class:`CreateAccount`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`CreateAccount`.
"""
destination = account_xdr_object(self.destination)
create_account_op = Xdr.types.CreateAccountOp(
destination, Operation.to_xdr_amount(self.starting_balance))
self.body.type = Xdr.const.CREATE_ACCOUNT
self.body.createAccountOp = create_account_op
return super(CreateAccount, self).to_xdr_object()
|
Creates a :class:`CreateAccount` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`CreateAccount` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
destination = encode_check(
'account',
op_xdr_object.body.createAccountOp.destination.ed25519).decode()
starting_balance = Operation.from_xdr_amount(
op_xdr_object.body.createAccountOp.startingBalance)
return cls(
source=source,
destination=destination,
starting_balance=starting_balance,
)
|
Creates an XDR Operation object that represents this
:class:`Payment`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`Payment`.
"""
asset = self.asset.to_xdr_object()
destination = account_xdr_object(self.destination)
amount = Operation.to_xdr_amount(self.amount)
payment_op = Xdr.types.PaymentOp(destination, asset, amount)
self.body.type = Xdr.const.PAYMENT
self.body.paymentOp = payment_op
return super(Payment, self).to_xdr_object()
|
Creates a :class:`Payment` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`Payment` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
destination = encode_check(
'account',
op_xdr_object.body.paymentOp.destination.ed25519).decode()
asset = Asset.from_xdr_object(op_xdr_object.body.paymentOp.asset)
amount = Operation.from_xdr_amount(op_xdr_object.body.paymentOp.amount)
return cls(
source=source,
destination=destination,
asset=asset,
amount=amount,
)
|
Creates an XDR Operation object that represents this
:class:`PathPayment`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`PathPayment`.
"""
destination = account_xdr_object(self.destination)
send_asset = self.send_asset.to_xdr_object()
dest_asset = self.dest_asset.to_xdr_object()
path = [asset.to_xdr_object() for asset in self.path]
path_payment = Xdr.types.PathPaymentOp(
send_asset, Operation.to_xdr_amount(self.send_max), destination,
dest_asset, Operation.to_xdr_amount(self.dest_amount), path)
self.body.type = Xdr.const.PATH_PAYMENT
self.body.pathPaymentOp = path_payment
return super(PathPayment, self).to_xdr_object()
|
Creates a :class:`PathPayment` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`PathPayment` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
destination = encode_check(
'account',
op_xdr_object.body.pathPaymentOp.destination.ed25519).decode()
send_asset = Asset.from_xdr_object(
op_xdr_object.body.pathPaymentOp.sendAsset)
dest_asset = Asset.from_xdr_object(
op_xdr_object.body.pathPaymentOp.destAsset)
send_max = Operation.from_xdr_amount(
op_xdr_object.body.pathPaymentOp.sendMax)
dest_amount = Operation.from_xdr_amount(
op_xdr_object.body.pathPaymentOp.destAmount)
path = []
if op_xdr_object.body.pathPaymentOp.path:
for x in op_xdr_object.body.pathPaymentOp.path:
path.append(Asset.from_xdr_object(x))
return cls(
source=source,
destination=destination,
send_asset=send_asset,
send_max=send_max,
dest_asset=dest_asset,
dest_amount=dest_amount,
path=path)
|
Creates an XDR Operation object that represents this
:class:`ChangeTrust`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`ChangeTrust`.
"""
line = self.line.to_xdr_object()
limit = Operation.to_xdr_amount(self.limit)
change_trust_op = Xdr.types.ChangeTrustOp(line, limit)
self.body.type = Xdr.const.CHANGE_TRUST
self.body.changeTrustOp = change_trust_op
return super(ChangeTrust, self).to_xdr_object()
|
Creates a :class:`ChangeTrust` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`ChangeTrust` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
line = Asset.from_xdr_object(op_xdr_object.body.changeTrustOp.line)
limit = Operation.from_xdr_amount(
op_xdr_object.body.changeTrustOp.limit)
return cls(source=source, asset=line, limit=limit)
|
Creates an XDR Operation object that represents this
:class:`AllowTrust`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`AllowTrust`.
"""
trustor = account_xdr_object(self.trustor)
length = len(self.asset_code)
assert length <= 12
pad_length = 4 - length if length <= 4 else 12 - length
# asset_code = self.asset_code + '\x00' * pad_length
# asset_code = bytearray(asset_code, encoding='utf-8')
asset_code = bytearray(self.asset_code, 'ascii') + b'\x00' * pad_length
asset = Xdr.nullclass()
if len(asset_code) == 4:
asset.type = Xdr.const.ASSET_TYPE_CREDIT_ALPHANUM4
asset.assetCode4 = asset_code
else:
asset.type = Xdr.const.ASSET_TYPE_CREDIT_ALPHANUM12
asset.assetCode12 = asset_code
allow_trust_op = Xdr.types.AllowTrustOp(trustor, asset, self.authorize)
self.body.type = Xdr.const.ALLOW_TRUST
self.body.allowTrustOp = allow_trust_op
return super(AllowTrust, self).to_xdr_object()
|
Creates a :class:`AllowTrust` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`AllowTrust` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
trustor = encode_check(
'account',
op_xdr_object.body.allowTrustOp.trustor.ed25519).decode()
authorize = op_xdr_object.body.allowTrustOp.authorize
asset_type = op_xdr_object.body.allowTrustOp.asset.type
if asset_type == Xdr.const.ASSET_TYPE_CREDIT_ALPHANUM4:
asset_code = (
op_xdr_object.body.allowTrustOp.asset.assetCode4.decode())
elif asset_type == Xdr.const.ASSET_TYPE_CREDIT_ALPHANUM12:
asset_code = (
op_xdr_object.body.allowTrustOp.asset.assetCode12.decode())
else:
raise NotImplementedError(
"Operation of asset_type={} is not implemented"
".".format(asset_type.type))
return cls(
source=source,
trustor=trustor,
authorize=authorize,
asset_code=asset_code)
|
Creates an XDR Operation object that represents this
:class:`SetOptions`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`SetOptions`.
"""
def assert_option_array(x):
if x is None:
return []
if not isinstance(x, list):
return [x]
return x
if self.inflation_dest is not None:
inflation_dest = [account_xdr_object(self.inflation_dest)]
else:
inflation_dest = []
self.clear_flags = assert_option_array(self.clear_flags)
self.set_flags = assert_option_array(self.set_flags)
self.master_weight = assert_option_array(self.master_weight)
self.low_threshold = assert_option_array(self.low_threshold)
self.med_threshold = assert_option_array(self.med_threshold)
self.high_threshold = assert_option_array(self.high_threshold)
self.home_domain = assert_option_array(self.home_domain)
req_signer_fields = (self.signer_address, self.signer_type,
self.signer_weight)
if all(signer_field is not None for signer_field in req_signer_fields):
signer = [
Xdr.types.Signer(
signer_key_xdr_object(self.signer_type,
self.signer_address),
self.signer_weight)
]
else:
signer = []
set_options_op = Xdr.types.SetOptionsOp(
inflation_dest, self.clear_flags, self.set_flags,
self.master_weight, self.low_threshold, self.med_threshold,
self.high_threshold, self.home_domain, signer)
self.body.type = Xdr.const.SET_OPTIONS
self.body.setOptionsOp = set_options_op
return super(SetOptions, self).to_xdr_object()
|
Creates a :class:`SetOptions` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`SetOptions` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
if not op_xdr_object.body.setOptionsOp.inflationDest:
inflation_dest = None
else:
inflation_dest = encode_check(
'account', op_xdr_object.body.setOptionsOp.inflationDest[0]
.ed25519).decode()
clear_flags = op_xdr_object.body.setOptionsOp.clearFlags # list
set_flags = op_xdr_object.body.setOptionsOp.setFlags
master_weight = op_xdr_object.body.setOptionsOp.masterWeight
low_threshold = op_xdr_object.body.setOptionsOp.lowThreshold
med_threshold = op_xdr_object.body.setOptionsOp.medThreshold
high_threshold = op_xdr_object.body.setOptionsOp.highThreshold
home_domain = op_xdr_object.body.setOptionsOp.homeDomain
if op_xdr_object.body.setOptionsOp.signer:
key = op_xdr_object.body.setOptionsOp.signer[0].key
if key.type == Xdr.const.SIGNER_KEY_TYPE_ED25519:
signer_address = encode_check('account', key.ed25519).decode()
signer_type = 'ed25519PublicKey'
if key.type == Xdr.const.SIGNER_KEY_TYPE_PRE_AUTH_TX:
signer_address = key.preAuthTx
signer_type = 'preAuthTx'
if key.type == Xdr.const.SIGNER_KEY_TYPE_HASH_X:
signer_address = key.hashX
signer_type = 'hashX'
signer_weight = op_xdr_object.body.setOptionsOp.signer[0].weight
else:
signer_address = None
signer_type = None
signer_weight = None
return cls(
source=source,
inflation_dest=inflation_dest,
clear_flags=clear_flags,
set_flags=set_flags,
master_weight=master_weight,
low_threshold=low_threshold,
med_threshold=med_threshold,
high_threshold=high_threshold,
home_domain=home_domain,
signer_address=signer_address,
signer_type=signer_type,
signer_weight=signer_weight)
|
Creates an XDR Operation object that represents this
:class:`ManageOffer`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`ManageOffer`.
"""
selling = self.selling.to_xdr_object()
buying = self.buying.to_xdr_object()
price = Operation.to_xdr_price(self.price)
price = Xdr.types.Price(price['n'], price['d'])
amount = Operation.to_xdr_amount(self.amount)
manage_offer_op = Xdr.types.ManageOfferOp(selling, buying, amount,
price, self.offer_id)
self.body.type = Xdr.const.MANAGE_OFFER
self.body.manageOfferOp = manage_offer_op
return super(ManageOffer, self).to_xdr_object()
|
Creates an XDR Operation object that represents this
:class:`CreatePassiveOffer`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`CreatePassiveOffer`.
"""
selling = self.selling.to_xdr_object()
buying = self.buying.to_xdr_object()
price = Operation.to_xdr_price(self.price)
price = Xdr.types.Price(price['n'], price['d'])
amount = Operation.to_xdr_amount(self.amount)
create_passive_offer_op = Xdr.types.CreatePassiveOfferOp(
selling, buying, amount, price)
self.body.type = Xdr.const.CREATE_PASSIVE_OFFER
self.body.createPassiveOfferOp = create_passive_offer_op
return super(CreatePassiveOffer, self).to_xdr_object()
|
Creates a :class:`CreatePassiveOffer` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`CreatePassiveOffer` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
selling = Asset.from_xdr_object(
op_xdr_object.body.createPassiveOfferOp.selling)
buying = Asset.from_xdr_object(
op_xdr_object.body.createPassiveOfferOp.buying)
amount = Operation.from_xdr_amount(
op_xdr_object.body.createPassiveOfferOp.amount)
n = op_xdr_object.body.createPassiveOfferOp.price.n
d = op_xdr_object.body.createPassiveOfferOp.price.d
price = division(n, d)
return cls(
source=source,
selling=selling,
buying=buying,
amount=amount,
price=price)
|
Creates an XDR Operation object that represents this
:class:`AccountMerge`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`AccountMerge`.
"""
destination = account_xdr_object(self.destination)
self.body.type = Xdr.const.ACCOUNT_MERGE
self.body.destination = destination
return super(AccountMerge, self).to_xdr_object()
|
Creates a :class:`AccountMerge` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`AccountMerge` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
destination = encode_check(
'account', op_xdr_object.body.destination.ed25519).decode()
return cls(source=source, destination=destination)
|
Creates an XDR Operation object that represents this
:class:`Inflation`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`Inflation`.
"""
self.body.type = Xdr.const.INFLATION
return super(Inflation, self).to_xdr_object()
|
Creates a :class:`Inflation` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`Inflation` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
return cls(source=source)
|
Creates an XDR Operation object that represents this
:class:`ManageData`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`ManageData`.
"""
data_name = bytearray(self.data_name, encoding='utf-8')
if self.data_value is not None:
if isinstance(self.data_value, bytes):
data_value = [bytearray(self.data_value)]
else:
data_value = [bytearray(self.data_value, 'utf-8')]
else:
data_value = []
manage_data_op = Xdr.types.ManageDataOp(data_name, data_value)
self.body.type = Xdr.const.MANAGE_DATA
self.body.manageDataOp = manage_data_op
return super(ManageData, self).to_xdr_object()
|
Creates a :class:`ManageData` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`ManageData` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
data_name = op_xdr_object.body.manageDataOp.dataName.decode()
if op_xdr_object.body.manageDataOp.dataValue:
data_value = op_xdr_object.body.manageDataOp.dataValue[0]
else:
data_value = None
return cls(source=source, data_name=data_name, data_value=data_value)
|
Creates an XDR Operation object that represents this
:class:`BumpSequence`.
|
def to_xdr_object(self):
"""Creates an XDR Operation object that represents this
:class:`BumpSequence`.
"""
bump_sequence_op = Xdr.types.BumpSequenceOp(self.bump_to)
self.body.type = Xdr.const.BUMP_SEQUENCE
self.body.bumpSequenceOp = bump_sequence_op
return super(BumpSequence, self).to_xdr_object()
|
Creates a :class:`BumpSequence` object from an XDR Operation
object.
|
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`BumpSequence` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed25519).decode()
bump_to = op_xdr_object.body.bumpSequenceOp.bumpTo
return cls(source=source, bump_to=bump_to)
|
Creates an XDR Memo object for a transaction with MEMO_TEXT.
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_TEXT."""
return Xdr.types.Memo(type=Xdr.const.MEMO_TEXT, text=self.text)
|
Creates an XDR Memo object for a transaction with MEMO_HASH.
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_HASH."""
return Xdr.types.Memo(type=Xdr.const.MEMO_HASH, hash=self.memo_hash)
|
Creates an XDR Memo object for a transaction with MEMO_RETURN.
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_RETURN."""
return Xdr.types.Memo(
type=Xdr.const.MEMO_RETURN, retHash=self.memo_return)
|
Append an :class:`Operation <stellar_base.operation.Operation>` to
the list of operations.
Add the operation specified if it doesn't already exist in the list of
operations of this :class:`Builder` instance.
:param operation: The operation to append to the list of operations.
:type operation: :class:`Operation`
:return: This builder instance.
|
def append_op(self, operation):
"""Append an :class:`Operation <stellar_base.operation.Operation>` to
the list of operations.
Add the operation specified if it doesn't already exist in the list of
operations of this :class:`Builder` instance.
:param operation: The operation to append to the list of operations.
:type operation: :class:`Operation`
:return: This builder instance.
"""
if operation not in self.ops:
self.ops.append(operation)
return self
|
Append a :class:`CreateAccount
<stellar_base.operation.CreateAccount>` operation to the list of
operations.
:param str destination: Account address that is created and funded.
:param str starting_balance: Amount of XLM to send to the newly created
account. This XLM comes from the source account.
:param str source: The source address to deduct funds from to fund the
new account.
:return: This builder instance.
|
def append_create_account_op(self,
destination,
starting_balance,
source=None):
"""Append a :class:`CreateAccount
<stellar_base.operation.CreateAccount>` operation to the list of
operations.
:param str destination: Account address that is created and funded.
:param str starting_balance: Amount of XLM to send to the newly created
account. This XLM comes from the source account.
:param str source: The source address to deduct funds from to fund the
new account.
:return: This builder instance.
"""
op = operation.CreateAccount(destination, starting_balance, source)
return self.append_op(op)
|
append_trust_op will be deprecated in the future, use append_change_trust_op instead.
Append a :class:`ChangeTrust <stellar_base.operation.ChangeTrust>`
operation to the list of operations.
:param str destination: The issuer address for the asset.
:param str code: The asset code for the asset.
:param str limit: The limit of the new trustline.
:param str source: The source address to add the trustline to.
:return: This builder instance.
|
def append_trust_op(self, destination, code, limit=None, source=None): # pragma: no cover
"""append_trust_op will be deprecated in the future, use append_change_trust_op instead.
Append a :class:`ChangeTrust <stellar_base.operation.ChangeTrust>`
operation to the list of operations.
:param str destination: The issuer address for the asset.
:param str code: The asset code for the asset.
:param str limit: The limit of the new trustline.
:param str source: The source address to add the trustline to.
:return: This builder instance.
"""
warnings.warn(
"append_trust_op will be deprecated in the future, use append_change_trust_op instead.",
PendingDeprecationWarning
) # pragma: no cover
return self.append_change_trust_op(asset_code=code, asset_issuer=destination, limit=limit,
source=source)
|
Append a :class:`ChangeTrust <stellar_base.operation.ChangeTrust>`
operation to the list of operations.
:param str asset_issuer: The issuer address for the asset.
:param str asset_code: The asset code for the asset.
:param str limit: The limit of the new trustline.
:param str source: The source address to add the trustline to.
:return: This builder instance.
|
def append_change_trust_op(self, asset_code, asset_issuer, limit=None, source=None):
"""Append a :class:`ChangeTrust <stellar_base.operation.ChangeTrust>`
operation to the list of operations.
:param str asset_issuer: The issuer address for the asset.
:param str asset_code: The asset code for the asset.
:param str limit: The limit of the new trustline.
:param str source: The source address to add the trustline to.
:return: This builder instance.
"""
asset = Asset(asset_code, asset_issuer)
op = operation.ChangeTrust(asset, limit, source)
return self.append_op(op)
|
Append a :class:`Payment <stellar_base.operation.Payment>` operation
to the list of operations.
:param str destination: Account address that receives the payment.
:param str amount: The amount of the currency to send in the payment.
:param str asset_code: The asset code for the asset to send.
:param asset_issuer: The address of the issuer of the asset.
:type asset_issuer: str, None
:param str source: The source address of the payment.
:return: This builder instance.
|
def append_payment_op(self,
destination,
amount,
asset_code='XLM',
asset_issuer=None,
source=None):
"""Append a :class:`Payment <stellar_base.operation.Payment>` operation
to the list of operations.
:param str destination: Account address that receives the payment.
:param str amount: The amount of the currency to send in the payment.
:param str asset_code: The asset code for the asset to send.
:param asset_issuer: The address of the issuer of the asset.
:type asset_issuer: str, None
:param str source: The source address of the payment.
:return: This builder instance.
"""
asset = Asset(code=asset_code, issuer=asset_issuer)
op = operation.Payment(destination, asset, amount, source)
return self.append_op(op)
|
Append a :class:`PathPayment <stellar_base.operation.PathPayment>`
operation to the list of operations.
:param str destination: The destination address (Account ID) for the
payment.
:param str send_code: The asset code for the source asset deducted from
the source account.
:param send_issuer: The address of the issuer of the source asset.
:type send_issuer: str, None
:param str send_max: The maximum amount of send asset to deduct
(excluding fees).
:param str dest_code: The asset code for the final destination asset
sent to the recipient.
:param dest_issuer: Account address that receives the payment.
:type dest_issuer: str, None
:param str dest_amount: The amount of destination asset the destination
account receives.
:param list path: A list of asset tuples, each tuple containing a
(asset_code, asset_issuer) for each asset in the path. For the native
asset, `None` is used for the asset_issuer.
:param str source: The source address of the path payment.
:return: This builder instance.
|
def append_path_payment_op(self,
destination,
send_code,
send_issuer,
send_max,
dest_code,
dest_issuer,
dest_amount,
path,
source=None):
"""Append a :class:`PathPayment <stellar_base.operation.PathPayment>`
operation to the list of operations.
:param str destination: The destination address (Account ID) for the
payment.
:param str send_code: The asset code for the source asset deducted from
the source account.
:param send_issuer: The address of the issuer of the source asset.
:type send_issuer: str, None
:param str send_max: The maximum amount of send asset to deduct
(excluding fees).
:param str dest_code: The asset code for the final destination asset
sent to the recipient.
:param dest_issuer: Account address that receives the payment.
:type dest_issuer: str, None
:param str dest_amount: The amount of destination asset the destination
account receives.
:param list path: A list of asset tuples, each tuple containing a
(asset_code, asset_issuer) for each asset in the path. For the native
asset, `None` is used for the asset_issuer.
:param str source: The source address of the path payment.
:return: This builder instance.
"""
# path: a list of asset tuple which contains asset_code and asset_issuer,
# [(asset_code, asset_issuer), (asset_code, asset_issuer)] for native asset you can deliver
# ('XLM', None)
send_asset = Asset(send_code, send_issuer)
dest_asset = Asset(dest_code, dest_issuer)
assets = []
for p in path:
assets.append(Asset(p[0], p[1]))
op = operation.PathPayment(destination, send_asset, send_max,
dest_asset, dest_amount, assets, source)
return self.append_op(op)
|
Append an :class:`AllowTrust <stellar_base.operation.AllowTrust>`
operation to the list of operations.
:param str trustor: The account of the recipient of the trustline.
:param str asset_code: The asset of the trustline the source account
is authorizing. For example, if an anchor wants to allow another
account to hold its USD credit, the type is USD:anchor.
:param bool authorize: Flag indicating whether the trustline is
authorized.
:param str source: The source address that is establishing the trust in
the allow trust operation.
:return: This builder instance.
|
def append_allow_trust_op(self,
trustor,
asset_code,
authorize,
source=None):
"""Append an :class:`AllowTrust <stellar_base.operation.AllowTrust>`
operation to the list of operations.
:param str trustor: The account of the recipient of the trustline.
:param str asset_code: The asset of the trustline the source account
is authorizing. For example, if an anchor wants to allow another
account to hold its USD credit, the type is USD:anchor.
:param bool authorize: Flag indicating whether the trustline is
authorized.
:param str source: The source address that is establishing the trust in
the allow trust operation.
:return: This builder instance.
"""
op = operation.AllowTrust(trustor, asset_code, authorize, source)
return self.append_op(op)
|
Append a :class:`SetOptions <stellar_base.operation.SetOptions>`
operation to the list of operations.
.. _Accounts:
https://www.stellar.org/developers/guides/concepts/accounts.html
:param str inflation_dest: The address in which to send inflation to on
an :class:`Inflation <stellar_base.operation.Inflation>` operation.
:param int clear_flags: Indicates which flags to clear. For details
about the flags, please refer to Stellar's documentation on
`Accounts`_. The bit mask integer subtracts from the existing flags
of the account. This allows for setting specific bits without
knowledge of existing flags.
:param int set_flags: Indicates which flags to set. For details about
the flags, please refer to Stellar's documentation on `Accounts`_.
The bit mask integer adds onto the existing flags of the account.
This allows for setting specific bits without knowledge of existing
flags.
:param int master_weight: Weight of the master key. This account may
also add other keys with which to sign transactions using the
signer param.
:param int low_threshold: A number from 0-255 representing the
threshold this account sets on all operations it performs that have
a `low threshold
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_.
:param int med_threshold: A number from 0-255 representing the
threshold this account sets on all operations it performs that have
a `medium threshold
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_.
:param int high_threshold: A number from 0-255 representing the
threshold this account sets on all operations it performs that have
a `high threshold
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_.
:param str home_domain: Sets the home domain of an account. See
Stellar's documentation on `Federation
<https://www.stellar.org/developers/guides/concepts/federation.html>`_.
:param signer_address: The address of the new signer to add to the
source account.
:type signer_address: str, bytes
:param str signer_type: The type of signer to add to the account. Must
be in ('ed25519PublicKey', 'hashX', 'preAuthTx'). See Stellar's
documentation for `Multi-Sign
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_
for more information.
:param int signer_weight: The weight of the signer. If the weight is 0,
the signer will be deleted.
:param str source: The source address for which options are being set.
:return: This builder instance.
|
def append_set_options_op(self,
inflation_dest=None,
clear_flags=None,
set_flags=None,
master_weight=None,
low_threshold=None,
med_threshold=None,
high_threshold=None,
home_domain=None,
signer_address=None,
signer_type=None,
signer_weight=None,
source=None):
"""Append a :class:`SetOptions <stellar_base.operation.SetOptions>`
operation to the list of operations.
.. _Accounts:
https://www.stellar.org/developers/guides/concepts/accounts.html
:param str inflation_dest: The address in which to send inflation to on
an :class:`Inflation <stellar_base.operation.Inflation>` operation.
:param int clear_flags: Indicates which flags to clear. For details
about the flags, please refer to Stellar's documentation on
`Accounts`_. The bit mask integer subtracts from the existing flags
of the account. This allows for setting specific bits without
knowledge of existing flags.
:param int set_flags: Indicates which flags to set. For details about
the flags, please refer to Stellar's documentation on `Accounts`_.
The bit mask integer adds onto the existing flags of the account.
This allows for setting specific bits without knowledge of existing
flags.
:param int master_weight: Weight of the master key. This account may
also add other keys with which to sign transactions using the
signer param.
:param int low_threshold: A number from 0-255 representing the
threshold this account sets on all operations it performs that have
a `low threshold
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_.
:param int med_threshold: A number from 0-255 representing the
threshold this account sets on all operations it performs that have
a `medium threshold
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_.
:param int high_threshold: A number from 0-255 representing the
threshold this account sets on all operations it performs that have
a `high threshold
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_.
:param str home_domain: Sets the home domain of an account. See
Stellar's documentation on `Federation
<https://www.stellar.org/developers/guides/concepts/federation.html>`_.
:param signer_address: The address of the new signer to add to the
source account.
:type signer_address: str, bytes
:param str signer_type: The type of signer to add to the account. Must
be in ('ed25519PublicKey', 'hashX', 'preAuthTx'). See Stellar's
documentation for `Multi-Sign
<https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_
for more information.
:param int signer_weight: The weight of the signer. If the weight is 0,
the signer will be deleted.
:param str source: The source address for which options are being set.
:return: This builder instance.
"""
op = operation.SetOptions(inflation_dest, clear_flags, set_flags,
master_weight, low_threshold, med_threshold,
high_threshold, home_domain, signer_address,
signer_type, signer_weight, source)
return self.append_op(op)
|
Add a HashX signer to an account.
Add a HashX signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param hashx: The address of the new hashX signer.
:type hashx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
|
def append_hashx_signer(self, hashx, signer_weight, source=None):
"""Add a HashX signer to an account.
Add a HashX signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param hashx: The address of the new hashX signer.
:type hashx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=hashx,
signer_type='hashX',
signer_weight=signer_weight,
source=source)
|
Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param pre_auth_tx: The address of the new preAuthTx signer - obtained by calling `hash_meta` on the TransactionEnvelope.
:type pre_auth_tx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
|
def append_pre_auth_tx_signer(self,
pre_auth_tx,
signer_weight,
source=None):
"""Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param pre_auth_tx: The address of the new preAuthTx signer - obtained by calling `hash_meta` on the TransactionEnvelope.
:type pre_auth_tx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=pre_auth_tx,
signer_type='preAuthTx',
signer_weight=signer_weight,
source=source)
|
Append a :class:`ManageOffer <stellar_base.operation.ManageOffer>`
operation to the list of operations.
:param str selling_code: The asset code for the asset the offer creator
is selling.
:param selling_issuer: The issuing address for the asset the offer
creator is selling.
:type selling_issuer: str, None
:param str buying_code: The asset code for the asset the offer creator
is buying.
:param buying_issuer: The issuing address for the asset the offer
creator is selling.
:type buying_issuer: str, None
:param str amount: Amount of the asset being sold. Set to 0 if you want
to delete an existing offer.
:param price: Price of 1 unit of selling in terms of buying. You can pass
in a number as a string or a dict like `{n: numerator, d: denominator}`
:type price: str, dict
:param int offer_id: The ID of the offer. 0 for new offer. Set to
existing offer ID to update or delete.
:param str source: The source address that is managing an offer on
Stellar's distributed exchange.
:return: This builder instance.
|
def append_manage_offer_op(self,
selling_code,
selling_issuer,
buying_code,
buying_issuer,
amount,
price,
offer_id=0,
source=None):
"""Append a :class:`ManageOffer <stellar_base.operation.ManageOffer>`
operation to the list of operations.
:param str selling_code: The asset code for the asset the offer creator
is selling.
:param selling_issuer: The issuing address for the asset the offer
creator is selling.
:type selling_issuer: str, None
:param str buying_code: The asset code for the asset the offer creator
is buying.
:param buying_issuer: The issuing address for the asset the offer
creator is selling.
:type buying_issuer: str, None
:param str amount: Amount of the asset being sold. Set to 0 if you want
to delete an existing offer.
:param price: Price of 1 unit of selling in terms of buying. You can pass
in a number as a string or a dict like `{n: numerator, d: denominator}`
:type price: str, dict
:param int offer_id: The ID of the offer. 0 for new offer. Set to
existing offer ID to update or delete.
:param str source: The source address that is managing an offer on
Stellar's distributed exchange.
:return: This builder instance.
"""
selling = Asset(selling_code, selling_issuer)
buying = Asset(buying_code, buying_issuer)
op = operation.ManageOffer(selling, buying, amount, price, offer_id,
source)
return self.append_op(op)
|
Append a :class:`CreatePassiveOffer
<stellar_base.operation.CreatePassiveOffer>` operation to the list of
operations.
:param str selling_code: The asset code for the asset the offer creator
is selling.
:param selling_issuer: The issuing address for the asset the offer
creator is selling.
:type selling_issuer: str, None
:param str buying_code: The asset code for the asset the offer creator
is buying.
:param buying_issuer: The issuing address for the asset the offer
creator is selling.
:type buying_issuer: str, None
:param str amount: Amount of the asset being sold. Set to 0 if you want
to delete an existing offer.
:param price: Price of 1 unit of selling in terms of buying. You can pass
in a number as a string or a dict like `{n: numerator, d: denominator}`
:type price: str, dict
:param str source: The source address that is creating a passive offer
on Stellar's distributed exchange.
:return: This builder instance.
|
def append_create_passive_offer_op(self,
selling_code,
selling_issuer,
buying_code,
buying_issuer,
amount,
price,
source=None):
"""Append a :class:`CreatePassiveOffer
<stellar_base.operation.CreatePassiveOffer>` operation to the list of
operations.
:param str selling_code: The asset code for the asset the offer creator
is selling.
:param selling_issuer: The issuing address for the asset the offer
creator is selling.
:type selling_issuer: str, None
:param str buying_code: The asset code for the asset the offer creator
is buying.
:param buying_issuer: The issuing address for the asset the offer
creator is selling.
:type buying_issuer: str, None
:param str amount: Amount of the asset being sold. Set to 0 if you want
to delete an existing offer.
:param price: Price of 1 unit of selling in terms of buying. You can pass
in a number as a string or a dict like `{n: numerator, d: denominator}`
:type price: str, dict
:param str source: The source address that is creating a passive offer
on Stellar's distributed exchange.
:return: This builder instance.
"""
selling = Asset(selling_code, selling_issuer)
buying = Asset(buying_code, buying_issuer)
op = operation.CreatePassiveOffer(selling, buying, amount, price,
source)
return self.append_op(op)
|
Append a :class:`AccountMerge
<stellar_base.operation.AccountMerge>` operation to the list of
operations.
:param str destination: The ID of the offer. 0 for new offer. Set to
existing offer ID to update or delete.
:param str source: The source address that is being merged into the
destination account.
:return: This builder instance.
|
def append_account_merge_op(self, destination, source=None):
"""Append a :class:`AccountMerge
<stellar_base.operation.AccountMerge>` operation to the list of
operations.
:param str destination: The ID of the offer. 0 for new offer. Set to
existing offer ID to update or delete.
:param str source: The source address that is being merged into the
destination account.
:return: This builder instance.
"""
op = operation.AccountMerge(destination, source)
return self.append_op(op)
|
Append a :class:`Inflation
<stellar_base.operation.Inflation>` operation to the list of
operations.
:param str source: The source address that is running the inflation
operation.
:return: This builder instance.
|
def append_inflation_op(self, source=None):
"""Append a :class:`Inflation
<stellar_base.operation.Inflation>` operation to the list of
operations.
:param str source: The source address that is running the inflation
operation.
:return: This builder instance.
"""
op = operation.Inflation(source)
return self.append_op(op)
|
Append a :class:`ManageData <stellar_base.operation.ManageData>`
operation to the list of operations.
:param str data_name: String up to 64 bytes long. If this is a new Name
it will add the given name/value pair to the account. If this Name
is already present then the associated value will be modified.
:param data_value: If not present then the existing
Name will be deleted. If present then this value will be set in the
DataEntry. Up to 64 bytes long.
:type data_value: str, bytes, None
:param str source: The source account on which data is being managed.
operation.
:return: This builder instance.
|
def append_manage_data_op(self, data_name, data_value, source=None):
"""Append a :class:`ManageData <stellar_base.operation.ManageData>`
operation to the list of operations.
:param str data_name: String up to 64 bytes long. If this is a new Name
it will add the given name/value pair to the account. If this Name
is already present then the associated value will be modified.
:param data_value: If not present then the existing
Name will be deleted. If present then this value will be set in the
DataEntry. Up to 64 bytes long.
:type data_value: str, bytes, None
:param str source: The source account on which data is being managed.
operation.
:return: This builder instance.
"""
op = operation.ManageData(data_name, data_value, source)
return self.append_op(op)
|
Append a :class:`BumpSequence <stellar_base.operation.BumpSequence>`
operation to the list of operations.
Only available in protocol version 10 and above
:param int bump_to: Sequence number to bump to.
:param str source: The source address that is running the inflation
operation.
:return: This builder instance.
|
def append_bump_sequence_op(self, bump_to, source=None):
"""Append a :class:`BumpSequence <stellar_base.operation.BumpSequence>`
operation to the list of operations.
Only available in protocol version 10 and above
:param int bump_to: Sequence number to bump to.
:param str source: The source address that is running the inflation
operation.
:return: This builder instance.
"""
op = operation.BumpSequence(bump_to, source)
return self.append_op(op)
|
Set the memo for the transaction to a new :class:`TextMemo
<stellar_base.memo.TextMemo>`.
:param memo_text: The text for the memo to add.
:type memo_text: str, bytes
:return: This builder instance.
|
def add_text_memo(self, memo_text):
"""Set the memo for the transaction to a new :class:`TextMemo
<stellar_base.memo.TextMemo>`.
:param memo_text: The text for the memo to add.
:type memo_text: str, bytes
:return: This builder instance.
"""
memo_text = memo.TextMemo(memo_text)
return self.add_memo(memo_text)
|
Set the memo for the transaction to a new :class:`IdMemo
<stellar_base.memo.IdMemo>`.
:param int memo_id: A 64 bit unsigned integer to set as the memo.
:return: This builder instance.
|
def add_id_memo(self, memo_id):
"""Set the memo for the transaction to a new :class:`IdMemo
<stellar_base.memo.IdMemo>`.
:param int memo_id: A 64 bit unsigned integer to set as the memo.
:return: This builder instance.
"""
memo_id = memo.IdMemo(memo_id)
return self.add_memo(memo_id)
|
Set the memo for the transaction to a new :class:`HashMemo
<stellar_base.memo.HashMemo>`.
:param memo_hash: A 32 byte hash or hex encoded string to use as the memo.
:type memo_hash: bytes, str
:return: This builder instance.
|
def add_hash_memo(self, memo_hash):
"""Set the memo for the transaction to a new :class:`HashMemo
<stellar_base.memo.HashMemo>`.
:param memo_hash: A 32 byte hash or hex encoded string to use as the memo.
:type memo_hash: bytes, str
:return: This builder instance.
"""
memo_hash = memo.HashMemo(memo_hash)
return self.add_memo(memo_hash)
|
Set the memo for the transaction to a new :class:`RetHashMemo
<stellar_base.memo.RetHashMemo>`.
:param bytes memo_return: A 32 byte hash or hex encoded string intended to be interpreted as
the hash of the transaction the sender is refunding.
:type memo_return: bytes, str
:return: This builder instance.
|
def add_ret_hash_memo(self, memo_return):
"""Set the memo for the transaction to a new :class:`RetHashMemo
<stellar_base.memo.RetHashMemo>`.
:param bytes memo_return: A 32 byte hash or hex encoded string intended to be interpreted as
the hash of the transaction the sender is refunding.
:type memo_return: bytes, str
:return: This builder instance.
"""
memo_return = memo.RetHashMemo(memo_return)
return self.add_memo(memo_return)
|
Append a :class:`Payment <stellar_base.operation.Payment>` operation
to the list of operations using federation on the destination address.
Translates the destination stellar address to an account ID via
:func:`federation <stellar_base.federation.federation>`, before
creating a new payment operation via :meth:`append_payment_op`.
:param str fed_address: A Stellar Address that needs to be translated
into a valid account ID via federation.
:param str amount: The amount of the currency to send in the payment.
:param str asset_code: The asset code for the asset to send.
:param str asset_issuer: The address of the issuer of the asset.
:param str source: The source address of the payment.
:param bool allow_http: When set to `True`, connections to insecure http protocol federation servers
will be allowed. Must be set to `False` in production. Default: `False`.
:return: This builder instance.
|
def federation_payment(self,
fed_address,
amount,
asset_code='XLM',
asset_issuer=None,
source=None,
allow_http=False):
"""Append a :class:`Payment <stellar_base.operation.Payment>` operation
to the list of operations using federation on the destination address.
Translates the destination stellar address to an account ID via
:func:`federation <stellar_base.federation.federation>`, before
creating a new payment operation via :meth:`append_payment_op`.
:param str fed_address: A Stellar Address that needs to be translated
into a valid account ID via federation.
:param str amount: The amount of the currency to send in the payment.
:param str asset_code: The asset code for the asset to send.
:param str asset_issuer: The address of the issuer of the asset.
:param str source: The source address of the payment.
:param bool allow_http: When set to `True`, connections to insecure http protocol federation servers
will be allowed. Must be set to `False` in production. Default: `False`.
:return: This builder instance.
"""
fed_info = federation(
address_or_id=fed_address, fed_type='name', allow_http=allow_http)
if not fed_info or not fed_info.get('account_id'):
raise FederationError(
'Cannot determine Stellar Address to Account ID translation '
'via Federation server.')
self.append_payment_op(fed_info['account_id'], amount, asset_code,
asset_issuer, source)
memo_type = fed_info.get('memo_type')
if memo_type is not None and memo_type in ('text', 'id', 'hash'):
getattr(self, 'add_' + memo_type.lower() + '_memo')(fed_info['memo'])
|
Generate a :class:`Transaction
<stellar_base.transaction.Transaction>` object from the list of
operations contained within this object.
:return: A transaction representing all of the operations that have
been appended to this builder.
:rtype: :class:`Transaction <stellar_base.transaction.Transaction>`
|
def gen_tx(self):
"""Generate a :class:`Transaction
<stellar_base.transaction.Transaction>` object from the list of
operations contained within this object.
:return: A transaction representing all of the operations that have
been appended to this builder.
:rtype: :class:`Transaction <stellar_base.transaction.Transaction>`
"""
if not self.address:
raise StellarAddressInvalidError('Transaction does not have any source address.')
if self.sequence is None:
raise SequenceError('No sequence is present, maybe not funded?')
tx = Transaction(
source=self.address,
sequence=self.sequence,
time_bounds=self.time_bounds,
memo=self.memo,
fee=self.fee * len(self.ops),
operations=self.ops)
self.tx = tx
return tx
|
Create an XDR object representing this builder's transaction to be
sent over via the Compliance protocol (notably, with a sequence number
of 0).
Intentionally, the XDR object is returned without any signatures on the
transaction.
See `Stellar's documentation on its Compliance Protocol
<https://www.stellar.org/developers/guides/compliance-protocol.html>`_
for more information.
|
def gen_compliance_xdr(self):
"""Create an XDR object representing this builder's transaction to be
sent over via the Compliance protocol (notably, with a sequence number
of 0).
Intentionally, the XDR object is returned without any signatures on the
transaction.
See `Stellar's documentation on its Compliance Protocol
<https://www.stellar.org/developers/guides/compliance-protocol.html>`_
for more information.
"""
sequence = self.sequence
self.sequence = -1
tx_xdr = self.gen_tx().xdr()
self.sequence = sequence
return tx_xdr
|
Create a :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` via an XDR
object.
In addition, sets the fields of this builder (the transaction envelope,
transaction, operations, source, etc.) to all of the fields in the
provided XDR transaction envelope.
:param xdr: The XDR object representing the transaction envelope to
which this builder is setting its state to.
:type xdr: bytes, str
|
def import_from_xdr(self, xdr):
"""Create a :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` via an XDR
object.
In addition, sets the fields of this builder (the transaction envelope,
transaction, operations, source, etc.) to all of the fields in the
provided XDR transaction envelope.
:param xdr: The XDR object representing the transaction envelope to
which this builder is setting its state to.
:type xdr: bytes, str
"""
te = Te.from_xdr(xdr)
if self.network.upper() in NETWORKS:
te.network_id = Network(NETWORKS[self.network]).network_id()
else:
te.network_id = Network(self.network).network_id()
self.te = te
self.tx = te.tx # with a different source or not .
self.ops = te.tx.operations
self.address = te.tx.source
self.sequence = te.tx.sequence - 1
time_bounds_in_xdr = te.tx.time_bounds
if time_bounds_in_xdr:
self.time_bounds = {
'maxTime': time_bounds_in_xdr[0].maxTime,
'minTime': time_bounds_in_xdr[0].minTime
}
else:
self.time_bounds = None
self.memo = te.tx.memo
return self
|
Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
not provided when this class was originaly instantiated, or if
another key is being utilized to sign the transaction envelope.
|
def sign(self, secret=None):
"""Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
not provided when this class was originaly instantiated, or if
another key is being utilized to sign the transaction envelope.
"""
keypair = self.keypair if not secret else Keypair.from_seed(secret)
self.gen_te()
self.te.sign(keypair)
|
Sign the generated transaction envelope using a Hash(x) signature.
:param preimage: The value to be hashed and used as a signer on the
transaction envelope.
:type preimage: str, bytes
|
def sign_preimage(self, preimage):
"""Sign the generated transaction envelope using a Hash(x) signature.
:param preimage: The value to be hashed and used as a signer on the
transaction envelope.
:type preimage: str, bytes
"""
if self.te is None:
self.gen_te()
self.te.sign_hashX(preimage)
|
Create a new builder based off of this one with its sequence number
incremented.
:return: A new Builder instance
:rtype: :class:`Builder`
|
def next_builder(self):
"""Create a new builder based off of this one with its sequence number
incremented.
:return: A new Builder instance
:rtype: :class:`Builder`
"""
sequence = self.sequence + 1
next_builder = Builder(
horizon_uri=self.horizon.horizon_uri,
address=self.address,
network=self.network,
sequence=sequence,
fee=self.fee)
next_builder.keypair = self.keypair
return next_builder
|
Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
|
def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.account(self.address)
return int(address.get('sequence'))
|
Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
|
def to_dict(self):
"""Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
"""
rv = {'code': self.code}
if not self.is_native():
rv['issuer'] = self.issuer
rv['type'] = self.type
else:
rv['type'] = 'native'
return rv
|
Create an XDR object for this :class:`Asset`.
:return: An XDR Asset object
|
def to_xdr_object(self):
"""Create an XDR object for this :class:`Asset`.
:return: An XDR Asset object
"""
if self.is_native():
xdr_type = Xdr.const.ASSET_TYPE_NATIVE
return Xdr.types.Asset(type=xdr_type)
else:
x = Xdr.nullclass()
length = len(self.code)
pad_length = 4 - length if length <= 4 else 12 - length
x.assetCode = bytearray(self.code, 'ascii') + b'\x00' * pad_length
x.issuer = account_xdr_object(self.issuer)
if length <= 4:
xdr_type = Xdr.const.ASSET_TYPE_CREDIT_ALPHANUM4
return Xdr.types.Asset(type=xdr_type, alphaNum4=x)
else:
xdr_type = Xdr.const.ASSET_TYPE_CREDIT_ALPHANUM12
return Xdr.types.Asset(type=xdr_type, alphaNum12=x)
|
Create an base64 encoded XDR string for this :class:`Asset`.
:return str: A base64 encoded XDR object representing this
:class:`Asset`.
|
def xdr(self):
"""Create an base64 encoded XDR string for this :class:`Asset`.
:return str: A base64 encoded XDR object representing this
:class:`Asset`.
"""
asset = Xdr.StellarXDRPacker()
asset.pack_Asset(self.to_xdr_object())
return base64.b64encode(asset.get_buffer())
|
Create a :class:`Asset` from an XDR Asset object.
:param asset_xdr_object: The XDR Asset object.
:return: A new :class:`Asset` object from the given XDR Asset object.
|
def from_xdr_object(cls, asset_xdr_object):
"""Create a :class:`Asset` from an XDR Asset object.
:param asset_xdr_object: The XDR Asset object.
:return: A new :class:`Asset` object from the given XDR Asset object.
"""
if asset_xdr_object.type == Xdr.const.ASSET_TYPE_NATIVE:
return Asset.native()
elif asset_xdr_object.type == Xdr.const.ASSET_TYPE_CREDIT_ALPHANUM4:
issuer = encode_check(
'account', asset_xdr_object.alphaNum4.issuer.ed25519).decode()
code = asset_xdr_object.alphaNum4.assetCode.decode().rstrip('\x00')
else:
issuer = encode_check(
'account',
asset_xdr_object.alphaNum12.issuer.ed25519).decode()
code = (
asset_xdr_object.alphaNum12.assetCode.decode().rstrip('\x00'))
return cls(code, issuer)
|
Create an :class:`Asset` object from its base64 encoded XDR
representation.
:param bytes xdr: The base64 encoded XDR Asset object.
:return: A new :class:`Asset` object from its encoded XDR
representation.
|
def from_xdr(cls, xdr):
"""Create an :class:`Asset` object from its base64 encoded XDR
representation.
:param bytes xdr: The base64 encoded XDR Asset object.
:return: A new :class:`Asset` object from its encoded XDR
representation.
"""
xdr_decoded = base64.b64decode(xdr)
asset = Xdr.StellarXDRUnpacker(xdr_decoded)
asset_xdr_object = asset.unpack_Asset()
asset = Asset.from_xdr_object(asset_xdr_object)
return asset
|
r'[A-Za-z][A-Za-z0-9_]*
|
def t_ID(t):
r'[A-Za-z][A-Za-z0-9_]*'
if t.value in keywords:
t.type = t.value.upper()
return t
|
constant_def : CONST ID EQUALS constant SEMI
|
def p_constant_def(t):
"""constant_def : CONST ID EQUALS constant SEMI"""
global name_dict
id = t[2]
value = t[4]
lineno = t.lineno(1)
if id_unique(id, 'constant', lineno):
name_dict[id] = const_info(id, value, lineno)
|
optional_value : value
| empty
|
def p_optional_value(t):
"""optional_value : value
| empty"""
# return value or None.
t[0] = t[1]
# Note this must be unsigned
value = t[0]
if value is None or value[0].isdigit():
return
msg = ''
if value[0] == '-':
msg = "Can't use negative index %s" % value
elif value not in name_dict:
msg = "Can't derefence index %s" % value
else:
data = name_dict[value]
if data.type != 'const':
msg = "Can't use non-constant %s %s as index" % (data.type, value)
elif not data.positive:
msg = "Can't use negative index %s" % value
if msg:
global error_occurred
error_occurred = True
print(u"ERROR - {0:s} near line {1:d}".format(msg, t.lineno(1)))
|
type_def : TYPEDEF declaration SEMI
|
def p_type_def_1(t):
"""type_def : TYPEDEF declaration SEMI"""
# declarations is a type_info
d = t[2]
lineno = t.lineno(1)
sortno = t.lineno(3) + 0.5
if d.type == 'void':
global error_occurred
error_occurred = True
print(
u"ERROR - can't use void in typedef at line {0:d}".format(lineno))
return
d.lineno = lineno
if id_unique(d.id, d.type, lineno):
if d.type == 'enum':
info = d.create_enum(lineno, sortno)
elif d.type == 'struct':
info = d.create_struct(lineno, sortno)
elif d.type == 'union':
info = d.create_union(lineno, sortno)
else:
info = d
name_dict[d.id] = info
|
type_def : ENUM ID enum_body SEMI
|
def p_type_def_2(t):
"""type_def : ENUM ID enum_body SEMI"""
id = t[2]
body = t[3]
lineno = t.lineno(1)
sortno = t.lineno(4) + 0.5
if id_unique(id, 'enum', lineno):
name_dict[id] = enum_info(id, body, lineno, sortno)
|
type_def : STRUCT ID struct_body SEMI
|
def p_type_def_3(t):
"""type_def : STRUCT ID struct_body SEMI"""
id = t[2]
body = t[3]
lineno = t.lineno(1)
if id_unique(id, 'struct', lineno):
name_dict[id] = struct_info(id, body, lineno)
|
type_def : UNION ID union_body SEMI
|
def p_type_def_4(t):
"""type_def : UNION ID union_body SEMI"""
id = t[2]
body = t[3]
lineno = t.lineno(1)
if id_unique(id, 'union', lineno):
name_dict[id] = union_info(id, body, lineno)
|
declaration : type_specifier STAR ID
|
def p_declaration_3(t):
"""declaration : type_specifier STAR ID"""
# encode this as the equivalent 'type_specifier ID LT 1 GT'
if not isinstance(t[1], type_info):
t[1] = type_info(t[1], t.lineno(1))
t[1].id = t[3]
t[1].array = True
t[1].fixed = False
t[1].len = '1'
t[0] = t[1]
|
type_specifier : INT
| HYPER
| FLOAT
| DOUBLE
| QUADRUPLE
| BOOL
| ID
| UNSIGNED
| enum_type_spec
| struct_type_spec
| union_type_spec
|
def p_type_specifier_2(t):
"""type_specifier : INT
| HYPER
| FLOAT
| DOUBLE
| QUADRUPLE
| BOOL
| ID
| UNSIGNED
| enum_type_spec
| struct_type_spec
| union_type_spec"""
# FRED - Note UNSIGNED is not in spec
if isinstance(t[1], type_info):
t[0] = t[1]
else:
t[0] = type_info(t[1], t.lineno(1))
|
enum_constant : ID EQUALS value
|
def p_enum_constant(t):
"""enum_constant : ID EQUALS value"""
global name_dict, error_occurred
id = t[1]
value = t[3]
lineno = t.lineno(1)
if id_unique(id, 'enum', lineno):
info = name_dict[id] = const_info(id, value, lineno, enum=True)
if not (value[0].isdigit() or value[0] == '-'):
# We have a name instead of a constant, make sure it is defined
if value not in name_dict:
error_occurred = True
print("ERROR - can't derefence {0:s} at line {1:s}".format(
value, lineno))
elif not isinstance(name_dict[value], const_info):
error_occurred = True
print(
"ERROR - reference to {0:s} at line {1:s} is not a constant".
format(value, lineno))
else:
info.positive = name_dict[value].positive
t[0] = [info]
else:
t[0] = []
|
program_def : PROGRAM ID LBRACE version_def version_def_list RBRACE EQUALS constant SEMI
|
def p_program_def(t):
"""program_def : PROGRAM ID LBRACE version_def version_def_list RBRACE EQUALS constant SEMI"""
print("Ignoring program {0:s} = {1:s}".format(t[2], t[8]))
global name_dict
id = t[2]
value = t[8]
lineno = t.lineno(1)
if id_unique(id, 'program', lineno):
name_dict[id] = const_info(id, value, lineno)
|
version_def : VERSION ID LBRACE procedure_def procedure_def_list RBRACE EQUALS constant SEMI
|
def p_version_def(t):
"""version_def : VERSION ID LBRACE procedure_def procedure_def_list RBRACE EQUALS constant SEMI"""
global name_dict
id = t[2]
value = t[8]
lineno = t.lineno(1)
if id_unique(id, 'version', lineno):
name_dict[id] = const_info(id, value, lineno)
|
procedure_def : proc_return ID LPAREN proc_firstarg type_specifier_list RPAREN EQUALS constant SEMI
|
def p_procedure_def(t):
"""procedure_def : proc_return ID LPAREN proc_firstarg type_specifier_list RPAREN EQUALS constant SEMI"""
global name_dict
tid = t[2]
value = t[8]
lineno = t.lineno(1)
if id_unique(tid, 'procedure', lineno):
name_dict[tid] = const_info(tid, value, lineno)
|
Returns True if dict_id not already used. Otherwise, invokes error
|
def id_unique(dict_id, name, lineno):
"""Returns True if dict_id not already used. Otherwise, invokes error"""
if dict_id in name_dict:
global error_occurred
error_occurred = True
print(
"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}"
.format(name, dict_id, lineno, name_dict[dict_id]))
return False
else:
return True
|
Return xdr code for the body (part between braces) of big 3 types
|
def xdrbody(self, prefix=''):
"""Return xdr code for the body (part between braces) of big 3 types"""
body = ''
prefix += indent
if self.type == 'enum':
body = ''.join(
["%s,\n" % l.xdrout(prefix) for l in self.body[:-1]])
body += "%s\n" % self.body[-1].xdrout(prefix)
elif self.type == 'struct':
body = ''.join(["%s\n" % l.xdrout(prefix) for l in self.body])
elif self.type == 'union':
for l in self.body[1:-1]:
body += ''.join(["%scase %s:\n" % (prefix, case) \
for case in l.cases])
body += ''.join([
"%s\n" % d.xdrout(prefix + indent) for d in l.declarations
])
if self.body[-1].declarations:
body += "%sdefault:\n" % prefix + \
''.join(["%s\n" % d.xdrout(prefix + indent)
for d in self.body[-1].declarations])
return body
|
Encode a string using Base58 with a 4 character checksum
|
def b58encode_check(v):
"""Encode a string using Base58 with a 4 character checksum"""
digest = sha256(sha256(v).digest()).digest()
return b58encode(v + digest[:4])
|
Base58 encode or decode FILE, or standard input, to standard output.
|
def main():
'''Base58 encode or decode FILE, or standard input, to standard output.'''
import sys
import argparse
stdout = buffer(sys.stdout)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'file',
metavar='FILE',
nargs='?',
type=argparse.FileType('r'),
default='-')
parser.add_argument(
'-d', '--decode', action='store_true', help='decode data')
parser.add_argument(
'-c',
'--check',
action='store_true',
help='append a checksum before encoding')
args = parser.parse_args()
fun = {
(False, False): b58encode,
(False, True): b58encode_check,
(True, False): b58decode,
(True, True): b58decode_check
}[(args.decode, args.check)]
data = buffer(args.file).read().rstrip(b'\n')
try:
result = fun(data)
except Exception as e:
sys.exit(e)
if not isinstance(result, bytes):
result = result.encode('ascii')
stdout.write(result)
|
Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
|
def _Dhcpcd(self, interfaces, logger):
"""Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
dhcpcd = ['/sbin/dhcpcd']
try:
subprocess.check_call(dhcpcd + ['-x', interface])
except subprocess.CalledProcessError:
# Dhcpcd not yet running for this device.
logger.info('Dhcpcd not yet running for interface %s.', interface)
try:
subprocess.check_call(dhcpcd + [interface])
except subprocess.CalledProcessError:
# The interface is already active.
logger.warning('Could not activate interface %s.', interface)
|
Generate a dictionary mapping MAC address to Ethernet interfaces.
Returns:
dict, string MAC addresses mapped to the string network interface name.
|
def _CreateInterfaceMapSysfs(self):
"""Generate a dictionary mapping MAC address to Ethernet interfaces.
Returns:
dict, string MAC addresses mapped to the string network interface name.
"""
interfaces = {}
for interface in os.listdir('/sys/class/net'):
try:
mac_address = open(
'/sys/class/net/%s/address' % interface).read().strip()
except (IOError, OSError) as e:
message = 'Unable to determine MAC address for %s. %s.'
self.logger.warning(message, interface, str(e))
else:
interfaces[mac_address] = interface
return interfaces
|
Generate a dictionary mapping MAC address to Ethernet interfaces.
Returns:
dict, string MAC addresses mapped to the string network interface name.
|
def _CreateInterfaceMapNetifaces(self):
"""Generate a dictionary mapping MAC address to Ethernet interfaces.
Returns:
dict, string MAC addresses mapped to the string network interface name.
"""
interfaces = {}
for interface in netifaces.interfaces():
af_link = netifaces.ifaddresses(interface).get(netifaces.AF_LINK, [])
mac_address = next(iter(af_link), {}).get('addr', '')
# In some systems this field can come with an empty string or with the
# name of the interface when there is no MAC address associated with it.
# Check the regex to be sure.
if MAC_REGEX.match(mac_address):
interfaces[mac_address] = interface
else:
message = 'Unable to determine MAC address for %s.'
self.logger.warning(message, interface)
return interfaces
|
Context manager for creating a temporary directory.
Args:
prefix: string, the prefix for the temporary directory.
run_dir: string, the base directory location of the temporary directory.
Yields:
string, the temporary directory created.
|
def _CreateTempDir(prefix, run_dir=None):
"""Context manager for creating a temporary directory.
Args:
prefix: string, the prefix for the temporary directory.
run_dir: string, the base directory location of the temporary directory.
Yields:
string, the temporary directory created.
"""
temp_dir = tempfile.mkdtemp(prefix=prefix + '-', dir=run_dir)
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir)
|
Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory.
|
def _RunScripts(self, run_dir=None):
"""Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory.
"""
with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
try:
self.logger.info('Starting %s scripts.', self.script_type)
script_dict = self.retriever.GetScripts(dest_dir)
self.executor.RunScripts(script_dict)
finally:
self.logger.info('Finished running %s scripts.', self.script_type)
|
Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
|
def _GetInstanceConfig(self):
"""Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
"""
try:
instance_data = self.metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance attributes were not found.')
try:
project_data = self.metadata_dict['project']['attributes']
except KeyError:
project_data = {}
self.logger.warning('Project attributes were not found.')
return (instance_data.get('google-instance-configs')
or project_data.get('google-instance-configs'))
|
Run a script and log the streamed script output.
Args:
script: string, the file location of an executable script.
|
def _RunScript(self, script):
"""Run a script and log the streamed script output.
Args:
script: string, the file location of an executable script.
"""
process = subprocess.Popen(
script, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
while True:
for line in iter(process.stdout.readline, b''):
self.logger.info(line.decode('utf-8').rstrip('\n'))
if process.poll() is not None:
break
|
Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
|
def _GenerateSshKey(self, key_type, key_dest):
"""Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
"""
# Create a temporary file to save the created RSA keys.
with tempfile.NamedTemporaryFile(prefix=key_type, delete=True) as temp:
temp_key = temp.name
command = ['ssh-keygen', '-t', key_type, '-f', temp_key, '-N', '', '-q']
try:
self.logger.info('Generating SSH key %s.', key_dest)
subprocess.check_call(command)
except subprocess.CalledProcessError:
self.logger.warning('Could not create SSH key %s.', key_dest)
return
shutil.move(temp_key, key_dest)
shutil.move('%s.pub' % temp_key, '%s.pub' % key_dest)
file_utils.SetPermissions(key_dest, mode=0o600)
file_utils.SetPermissions('%s.pub' % key_dest, mode=0o644)
|
Initialize the SSH daemon.
|
def _StartSshd(self):
"""Initialize the SSH daemon."""
# Exit as early as possible.
# Instance setup systemd scripts block sshd from starting.
if os.path.exists(constants.LOCALBASE + '/bin/systemctl'):
return
elif (os.path.exists('/etc/init.d/ssh')
or os.path.exists('/etc/init/ssh.conf')):
subprocess.call(['service', 'ssh', 'start'])
subprocess.call(['service', 'ssh', 'reload'])
elif (os.path.exists('/etc/init.d/sshd')
or os.path.exists('/etc/init/sshd.conf')):
subprocess.call(['service', 'sshd', 'start'])
subprocess.call(['service', 'sshd', 'reload'])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.