stellarcn / py-stellar-base Goto Github PK
View Code? Open in Web Editor NEWStellar client library for the Python language
Home Page: https://stellar-sdk.readthedocs.io
License: Apache License 2.0
Stellar client library for the Python language
Home Page: https://stellar-sdk.readthedocs.io
License: Apache License 2.0
latest commit has broken compatibility with Python 3.5.
commit 2e8d2d6
@@ -34,7 +34,7 @@ def account_xdr_object(account):
def bytes_from_decode_data(s):
"""copy from base64._bytes_from_decode_data
"""
- if isinstance(s, str):
+ if isinstance(s, (str, unicode)):
try:
return s.encode('ascii')
except UnicodeEncodeError:
This fails for some reason, please see inline comments.
#!/usr/bin/python3
import requests
import json
from stellar_base.transaction_envelope import TransactionEnvelope as Te
from stellar_base.keypair import Keypair
from stellar_base.builder import Builder
url = 'https://horizon-testnet.stellar.org'
ana = Keypair.random()
bob = Keypair.random()
tom = Keypair.random()
args = {
'network': 'TESTNET',
'asset': 'EUR',
'amount': 1000000,
'limit': 1000000,
}
# Fund ana from friendbot
urlParam = url + '/friendbot?addr=' + ana.address().decode('ascii')
r = requests.get(urlParam)
assert 'hash' in json.loads(r.text), "\n" + urlParam + "\n" + r.text
# Build envelope in a problematic way
builder = Builder(network=args['network'])
builder.address = ana.address().decode('ascii')
builder.sequence = builder.get_sequence()
builder.append_create_account_op(bob.address().decode('ascii'), 1234, source=ana.address().decode('ascii'))
builder.append_set_options_op(
set_flags=3, # Authorization required (0x1) + Authorization revocable (0x2)
master_weight=1,
low_threshold=0,
med_threshold=0,
high_threshold=2,
signer_address=ana.address().decode('ascii'),
signer_weight=3,
source=bob.address().decode('ascii'))
builder.append_manage_data_op('Blah'+args['asset'].ljust(4, ' ')+tom.address().decode('ascii').ljust(56, ' '), bob.address().decode('ascii'), source=ana.address().decode('ascii'))
builder.append_trust_op(bob.address().decode('ascii'), args['asset'], limit=str(args['limit']), source=tom.address().decode('ascii'))
builder.append_allow_trust_op(tom.address().decode('ascii'), args['asset'], True, source=bob.address().decode('ascii'))
builder.append_payment_op(tom.address().decode('ascii'), args['amount'], args['asset'], bob.address().decode('ascii'), source=bob.address().decode('ascii'))
envelope = builder.gen_te()
envelope_xdr = envelope.xdr()
print(envelope_xdr)
# Something bad happens with xdr here, I have no clue where to look.
envelope_xdr2 = Te.from_xdr(envelope.xdr()).xdr()
print(envelope_xdr2)
# I suspect that problem happens with payment_op because
# assert succeeds if I comment out 'builder.append_payment_op...' line
assert envelope_xdr == envelope_xdr2 # should be true
Error in both Python2.7 and Python3.4
File "src/lib/stellar-sdk-py/stellar_base/horizon.py", line 52, in account
return query(url)
File "src/lib/stellar-sdk-py/stellar_base/horizon.py", line 19, in query
p = requests.get(url, params)
TypeError: get() takes 1 positional argument but 2 were given
instead of
send = Builder(private_key, network='PUBLIC', horizon=HORIZON_LIVE)
send.append_payment_op(to_addr, amount , 'XLM')
send.add_text_memo(memo)
send.sign()
status = send.submit()
something like this where the submit checks to see if signed. if unsigned it signs the tx?
send = Builder(private_key, network='PUBLIC', horizon=HORIZON_LIVE)
send.append_payment_op(to_addr, amount , 'XLM')
send.add_text_memo(memo)
status = send.submit()
Code within operation.ManageOffer
is unfinished and signing envelope with this Op, both Python2.7 and Python3.4 gives error.
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 20, in sign
tx_hash = self.hash_meta()
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 26, in hash_meta
return xdr_hash(self.signature_base())
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 35, in signature_base
tx.pack_Transaction(self.tx.to_xdr_object())
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1298, in pack_Transaction
self.pack_array(data.operations, self.pack_Operation)
File "/usr/lib/python2.7/xdrlib.py", line 131, in pack_array
self.pack_farray(n, list, pack_item)
File "/usr/lib/python2.7/xdrlib.py", line 126, in pack_farray
pack_item(item)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1200, in pack_Operation
if data.body.manageOfferOp is None:
AttributeError: type object 'nullclass' has no attribute 'manageOfferOp'
Add operation ManageData. As example in js-stellar-base it is done here
numpy will shortly stop supporting 2.x
Is it possible to use a custom node rather than "livenet" or "testnet" ?
Readme.md is incorrect per the implementation of the address.py.
"now you can check address.balance ,sequence ,flags ,signers, manage_data etc."
should be:
"now you can check address.balances ,sequence ,flags ,signers, manage_data etc."
(Added an "s" to balance for proper variable naming)
When using builder.append_set_options_op
to add a preAuthTx
signer I get the following exeption:
Exception: hashX or preAuthTx Signer must be 32 bytes
The length of the added hash is exactly 32 bytes.
Hello,
As @manran pointed out in #62, there is a general effort to add Key Derivation Methods for Stellar Accounts as covered in: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0005.md
Currently there is a reference implementation wallet in Go, NodeJS, and PHP. We should endeavor to adapt the Go version for Python:
https://github.com/stellar/go/tree/master/tools/stellar-hd-wallet
This code could potentially replace the work done in this SDK for the current simple mnemonic word list seed generation functionality in this SDK, since full support for UTF-8 (eg Chinese) is supported in BIP-39:
https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#Wordlist
I also thing that test-case 4 of SEP-0005 should be targeted, "Mnemonic (24 words + BIP 39 passphrase)" - this is the ideal for security in my opinion.
Spent last 6 hours chasing bug that caused Internal Server Error'
response, I though it was something in test-horizon but it turned out that requests.post() keyword params =/= data
and it was not sending to it any tx at all.
So should write tests for Horizon class.
Found during a debugging session. Root cause is wrong key name in opts. Fix in progress.
This line in TransactionEnvelope only allows access to the 2 builtin passphrases in NETWORKS. I created a standalone network using stellar's quickstart docker image. But I can't refer to it in the TransactionEnvelope.
Perhaps this would work. It's kind of verbose.
if 'network_id' in opts:
if opts['network_id'] in NETWORKS:
phrase = NETWORKS[opts['network_id']]
else:
phrase = opts['network_id']
else:
phrase = NETWORKS['TESTNET']
return Network(phrase).network_id()
We need better python docstrings...
At least for the builder and the address functions.. I propose we basically copy those from the javascript implementation which has beautiful docs.
http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
Using python 2.7, most up to date code from github. Section 4.1 from tutorial.
Traceback (most recent call last):
File "", line 1, in
File "/home/gitzman/anaconda3/envs/stellar/lib/python2.7/site-packages/stellar_base-0.1.0-py2.7.egg/stellar_base/builder.py", line 324, in submit
raise e
ValueError: No JSON object could be decoded
Problem: Friend creates transaction that also I need to sign, so he signs and sends envelope encoded as xdr to me. How to un-xdr the envelope?
I think it would be awesome to have method for envelope that builds it from xdr, for example
from stellar_base.transaction_envelope import TransactionEnvelope as Te
# Receive envelope through file, email or other means
xdr = b'AAAAAI6UOB1TLjF0uaFjdpMhzrl/7uRlfJhvT8HssDLIaaLbAAAAyAAMxkkAAAACAAAAAAAAAAEAAAAHdGVzdGluZwAAAAACAAAAAQAAAACOlDgdUy4xdLmhY3aTIc65f+7kZXyYb0/B7LAyyGmi2wAAAAEAAAAAjpQ4HVMuMXS5oWN2kyHOuX/u5GV8mG9PweywMshpotsAAAAAAAAAAABqz8AAAAABAAAAANrC8UJLKTDcDOweA35LPXC6c0TcHZpyRSAWwkbUEyAQAAAAAQAAAACOlDgdUy4xdLmhY3aTIc65f+7kZXyYb0/B7LAyyGmi2wAAAAAAAAAAAGrPwAAAAAAAAAAByGmi2wAAAEBPtGLy1fmXaaYnhbiWNMzRtZ37RdTSdDFpno807cXQIHA4DYaxwhCAph15eUSdZkG8uCKuRBRaKu0fbNneA0gO'
envelope = Te.from_xdr(xdr) # Enchantment
envelope.sign( signer )
horizon.submit( envelope.xdr() )
Maybe there are other better ways how to do this?
I get error TypeError: Can't convert 'bytes' object to str implicitly
when trying to sign the envelope that has TextMemo. If using NoneMemo, everything works. See the full error and code below.
Account Generated: GBEB4GEO6QBM4UNNRIAODMFYFPULUQCBHCFBK4N6HMWBLX4VD7FLNAFH
Account Generated: GBD3PW4PF7I7HRLEZM5CLFDGRXG7TXZIGX64KKUF2FPRUCNHFH664KMC
Traceback (most recent call last):
File "sample-error.py", line 68, in <module>
envelope.sign(Keypair.from_seed(anna['seed']))
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 20, in sign
tx_hash = self.hash_meta()
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 26, in hash_meta
return xdr_hash(self.signature_base())
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 35, in signature_base
tx.pack_Transaction(self.tx.to_xdr_object())
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1286, in pack_Transaction
self.pack_Memo(data.memo)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1241, in pack_Memo
self.pack_string(data.text)
File "/usr/local/lib/python3.5/xdrlib.py", line 108, in pack_string
self.pack_fstring(n, s)
File "/usr/local/lib/python3.5/xdrlib.py", line 100, in pack_fstring
data = data + (n - len(data)) * b'\0'
TypeError: Can't convert 'bytes' object to str implicitly
# coding:utf-8
import sys
sys.path.append('src/')
sys.path.append('src/lib/stellar-sdk-py')
from stellar_base.operation import Payment
from stellar_base.asset import Asset
from stellar_base.transaction import Transaction
from stellar_base.transaction_envelope import TransactionEnvelope as Te
from stellar_base.keypair import Keypair
from stellar_base.memo import *
url = 'https://horizon-testnet.stellar.org'
def newAccount(creator=False):
import requests
import simplejson as json
from stellar_base.keypair import Keypair
# Generate keys
kp = Keypair.random()
# Fund account
if(creator=='friendbot'):
# from Friendbot
urlParam = url + '/friendbot?addr=' + kp.address().decode('ascii')
r = requests.get(urlParam) # Get 1000 lumens
assert 'hash' in json.loads(r.text), "\n" + urlParam + "\n" + r.text
elif(creator):
assert False, "TODO"
else:
# Dont fund it
pass
print('Account Generated: ' + kp.address().decode('ascii'))
return {
'address': kp.address().decode('ascii'),
'seed': kp.seed().decode('ascii')
}
def fetchSeq(address):
assert address
import requests
import simplejson as json
return json.loads(requests.get(url+'/accounts/'+address).text)['sequence']
def announce(envelope_b64=False):
assert envelope_b64
import requests
import simplejson as json
r = requests.post(url+'/transactions', data={'tx': envelope_b64.decode('ascii')})
msg = json.loads(r.text)
if('hash' in msg):
print('Tx: ', msg['hash'])
else:
from pprintpp import pprint as pp # https://github.com/wolever/pprintpp
print('Tx warning: ')
pp(msg)
return msg
def packer(envelope=False):
assert envelope
import base64
from stellar_base.stellarxdr import StellarXDR_pack as Xdr
x = Xdr.STELLARXDRPacker()
x.pack_TransactionEnvelope(envelope.to_xdr_object())
return base64.b64encode(x.get_buffer())
# base info
anna = newAccount('friendbot')
bob = newAccount('friendbot')
operation = Payment({
'source': anna['address'],
'destination': bob['address'],
'asset': Asset.native(),
'amount': 10*10**6,
})
tx = Transaction(
source=anna['address'],
opts={
'seqNum': fetchSeq(anna['address']),
'timeBounds': [],
'memo': TextMemo('Just testing'),
'fee': 100,
'operations': [
operation,
],
},
)
envelope = Te(tx=tx, opts={"network_id": "TESTNET"})
envelope.sign(Keypair.from_seed(anna['seed']))
announce(packer(envelope))
Going through the READ.ME docs, I hit a major roadblock.
Typing this:
from stellar_base.keypair import Keypair
kp = Keypair.random()
GIves me this error:
Traceback (most recent call last):
File "D:/Stellar toybox.py", line 5, in
kp1 = Keypair.deterministic(m,index=1)
File "D:\lib\site-packages\stellar_base\keypair.py", line 35, in deterministic
return cls.from_raw_seed(seed)
File "D:\lib\site-packages\stellar_base\keypair.py", line 53, in from_raw_seed
signing_key = ed25519.SigningKey(raw_seed)
File "D:\lib\site-packages\ed25519\keys.py", line 85, in init
vk_s, sk_s = _ed25519.publickey(sk_s)
MemoryError
Huh? MemoryError?
Ok, so the first method creating Stellar key pair doesn't work for me, let's try the eecond method. It works, very well and...
It comes to here:
kp = Keypair.deterministic(m) #I typed this out without defining language as I wanted it to be in Standard English
Traceback (most recent call last):
File "D:/Stellar toybox.py", line 4, in
kp = Keypair.deterministic(m)
NameError: name 'Keypair' is not defined
Ok so it's not defined, let me scroll down more to see whether anything can help.
kp1 = Keypair.deterministic(m, lang='chinese', index=1)#Same error
kp2 = Keypair.deterministic(m, lang='chinese', index=2) #Same error
Here's my code, I typed it all out as I really wanted to learn how to use the python-base package. (Some errors might be due to my bad typing)
from stellar_base.utils import StellarMnemonic
sm = StellarMnemonic()
m = sm.generate()
kp1 = Keypair.deterministic(m,index=1)
kp2 = Keypair.deterministic(m,index=2)
I'm running through the documentation on the README.md file for creating a mnemonic keypair seed, and discovered that a mnemonic wordlist doesn't appear to be included, resulting in an ugly traceback for the user. Please see below:
Python 3.6.3 (default, Oct 9 2017, 12:07:10)
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from stellar_base.utils import StellarMnemonic
>>> sm = StellarMnemonic()
>>> m = sm.generate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/stellar_base/utils.py", line 236, in generate
ret = self.to_mnemonic(os.urandom(strength // 8))
File "/usr/local/lib/python3.6/site-packages/mnemonic/mnemonic.py", line 146, in to_mnemonic
if self.detect_language(' '.join(result)) == 'japanese': # Japanese must be joined by ideographic space.
File "/usr/local/lib/python3.6/site-packages/mnemonic/mnemonic.py", line 78, in detect_language
languages = cls.list_languages()
File "/usr/local/lib/python3.6/site-packages/stellar_base/utils.py", line 222, in list_languages
lang = [f.split('.')[0] for f in os.listdir(cls._get_directory()) if f.endswith('.txt')]
FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/stellar_base/wordlist'
I do see that the python3 module 'mnemonic' includes a Japanese and an English wordlist available at:
/usr/local/lib/python3.6/site-packages/mnemonic/wordlist/english.txt
...but I'm not sure if it meets all requirements for use with Stellar - eg, there are some 3-character words in the list and I wasn't sure if there were any minimum length requirements for seed words of 4+ or 5+ characters.
If we can use the one provided in the mnemonic module, I'm not sure if it can be referenced by this module within python or if we just need to duplicate it.
There are 2048 words in the wordlist I found. Is that enough "entropy" to be secure as a seed word list? Would that be 2048^12? 2048^24?
With Python3.5 works fine.
With Python2.7 TextMemo()
doesn't work.
'memo': TextMemo('A'), # Broken for now.
File "src/lib/stellar-sdk-py/stellar_base/memo.py", line 18, in __init__
length = len(bytes(text, encoding='utf-8'))
TypeError: str() takes at most 1 argument (2 given)
cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Isrc/ed25519-supercop-ref -Id:include -Id:include "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" /Tcsrc/ed25519-glue/ed25519module.c /Fobuild\temp.win-amd64-3.6\Release\src/ed25519-glue/ed25519module.obj
error: command 'cl.exe' failed: No such file or directory
tried pip installing it, got this.
Command "d:\python.exe -u -c "import setuptools, tokenize;file='C:\Users\HP\AppData\Local\Temp\pip-install-1x6uuvav\ed25519\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\HP\AppData\Local\Temp\pip-record-6__rcqcx\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\HP\AppData\Local\Temp\pip-install-1x6uuvav\ed25519\
tx = Builder(hotw['seed'], network='PUBLIC')
tx.append_path_payment_op(destination='GCKX3XVTPVNFXQWLQCIBZX6OOPOIUT7FOAZVNOFCNEIXEZFRFSPNZKZT', send_code='PHP',send_issuer='GAP5LETOV6YIE62YAM56STDANPRDO7ZFDBGSNHJQIYGGKSMOZAHOOS2S', send_max = '10', dest_code='PHP', dest_issuer='GBUQWP3BOUZX34TOND2QV7QQ7K7VJTG6VSE7WMLBTMDJLLAW7YKGU6EP',dest_amount='1', path=[])
tx.add_id_memo(memo_id)
tx.sign()
tx.submit()
Throws
AttributeError: 'NoneType' object has no attribute 'to_xdr_object'
# tx with SetOptions that has "Signer Public Key" and "Signer Weight" set
tx_b64="AAAAAICWoainP1dIvO1xv/MPunWGvb3MOnUB3AFsbH7KKehEAAAAZAAazYAAAAABAAAAAAAAAAAAAAABAAAAAAAAAAUAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAJyo6y9g/yze+SB68uAT/mWOGOSHYA64F4Po0qZeOjXRAAAAAwAAAAAAAAAA"
envelope = Te.from_xdr(tx_b64) # crashes here as below without changes in stellar_base/operations.py
envelope.sign(keypair=Keypair.from_seed(seed=seed)) # crashes here with changes in stellar_base/operations.py
----------------------------------------
Traceback (most recent call last):
...
envelope = Te.from_xdr(tx_b64)
File "/home/$USER/git/sr/py-stellar-base/stellar_base/transaction_envelope.py", line 62, in from_xdr
tx = Transaction.from_xdr_object(tx_xdr_object)
File "/home/$USER/git/sr/py-stellar-base/stellar_base/transaction.py", line 81, in from_xdr_object
operations.append(SetOptions.from_xdr_object(op))
File "/home/$USER/git/sr/py-stellar-base/stellar_base/operation.py", line 331, in from_xdr_object
signer_address = op_xdr_object.body.setOptionsOp.signer.pubKey.ed25519
AttributeError: 'list' object has no attribute 'pubKey'
----------------------------------------
If I change these lines in stellar_base/operations.py
lines 329-332
# Old version
if op_xdr_object.body.setOptionsOp.signer:
signer_address = op_xdr_object.body.setOptionsOp.signer.pubKey.ed25519
signer_weight = op_xdr_object.body.setOptionsOp.signer.weight
# New version
if op_xdr_object.body.setOptionsOp.signer:
signer_address = op_xdr_object.body.setOptionsOp.signer[0].pubKey.ed25519
signer_weight = op_xdr_object.body.setOptionsOp.signer[0].weight
then tx is made without errors but throws this error while trying to sign
----------------------------------------
Traceback (most recent call last):
File "/home/$USER/git/sr/py-stellar-base/stellar_base/utils.py", line 94, in decode_check
decoded = base64.b32decode(encoded)
File "/usr/lib/python3.4/base64.py", line 236, in b32decode
raise binascii.Error('Non-base32 digit found') from None
binascii.Error: Non-base32 digit found
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
...
envelope.sign(keypair=Keypair.from_seed(seed=seed))
File "/home/$USER/git/sr/py-stellar-base/stellar_base/transaction_envelope.py", line 22, in sign
tx_hash = self.hash_meta()
File "/home/$USER/git/sr/py-stellar-base/stellar_base/transaction_envelope.py", line 31, in hash_meta
return xdr_hash(self.signature_base())
File "/home/$USER/git/sr/py-stellar-base/stellar_base/transaction_envelope.py", line 40, in signature_base
tx.pack_Transaction(self.tx.to_xdr_object())
File "/home/$USER/git/sr/py-stellar-base/stellar_base/transaction.py", line 40, in to_xdr_object
operations = [o.to_xdr_object() for o in self.operations]
File "/home/$USER/git/sr/py-stellar-base/stellar_base/transaction.py", line 40, in <listcomp>
operations = [o.to_xdr_object() for o in self.operations]
File "/home/$USER/git/sr/py-stellar-base/stellar_base/operation.py", line 299, in to_xdr_object
signer = [Xdr.types.Signer(account_xdr_object(self.signer_address), self.signer_weight)]
File "/home/$USER/git/sr/py-stellar-base/stellar_base/utils.py", line 42, in account_xdr_object
public_key = decode_check('account', account)
File "/home/$USER/git/sr/py-stellar-base/stellar_base/utils.py", line 96, in decode_check
raise DecodeError('Incorrect padding')
stellar_base.utils.DecodeError: Incorrect padding
----------------------------------------
I am using last commit a4930eb in master branch
This is the response that I've got.
``` { "_links": { "account": { "href": "https://horizon-testnet.stellar.org/accounts/{account_id}", "templated": true }, "account_transactions": { "href": "https://horizon-testnet.stellar.org/accounts/{account_id}/transactions{?cursor,limit,order}", "templated": true }, "assets": { "href": "https://horizon-testnet.stellar.org/assets{?asset_code,asset_issuer,cursor,limit,order}", "templated": true }, "friendbot": { "href": "https://horizon-testnet.stellar.org/friendbot{?addr}", "templated": true }, "metrics": { "href": "https://horizon-testnet.stellar.org/metrics" }, "order_book": { "href": "https://horizon-testnet.stellar.org/order_book{?selling_asset_type,selling_asset_code,selling_issuer,buying_asset_type,buying_asset_code,buying_issuer,limit}", "templated": true }, "self": { "href": "https://horizon-testnet.stellar.org/" }, "transaction": { "href": "https://horizon-testnet.stellar.org/transactions/{hash}", "templated": true }, "transactions": { "href": "https://horizon-testnet.stellar.org/transactions{?cursor,limit,order}", "templated": true } }, "horizon_version": "snapshot-snapshots-1-gcfa216c", "core_version": "stellar-core 9.2.0rc5 (6dfee37f5e9effa9c655cf4884b97b72451fbdf0)", "history_latest_ledger": 7949569, "history_elder_ledger": 1, "core_latest_ledger": 7949569, "network_passphrase": "Test SDF Network ; September 2015", "protocol_version": 9 } ```A new account hasn't been created on the test network.
import requests
publickey = kp.address().decode()
url = 'https://horizon-testnet.stellar.org/friendbot'
r = requests.get(url, params={'addr': publickey})
The documentation for Address says one should pass in a Horizon object in the __init__
, but it fails at get()
because this line tries to append a string to a Horizon object. In fact, the Horizon object gets wrapped by another Horizon object here.
I'd prefer to pass in a Horizon object rather than a string. For now it seems the types and docs are inconsistent.
When calling builder.import_from_xdr
on an XDR that contains a set_opts
transaction which adds a preAuthTx
signer, I get the following exception:
Exception: Must be a valid strkey if not give signer_type
I did specify signer_type, of course.
What's the reason for limiting the number of operations to 100 in a transaction?
I have seen multi signature support in javascript. Is there a multi signature support in python implementation? If so, Could you explain how to do?
For example, I'd like to use the Python API to make the following type of query:
curl 'https://horizon-testnet.stellar.org/ledgers?cursor=&limit=1&order=desc'
And return the result data.
Once the ledger gives a transaction, I'd like to query the transaction in a similar fashion.
Is this possible?
Haven't had a chance to investigate further, but it looks like many of the classes in the package aren't showing up in the docs on RTD:
Hello
I use the pip install stellar-base but it does not work. Since I have Anaconda already, I tried conda install stellar-base but still it did not work. Plz help me if anyone knows why. Thanks
When I try load operation for this transaction https://horizon-testnet.stellar.org/transactions/4cab818a57ee33ef84b73888d2f458086316298c903b94f9b7673ca7f086cc49/operations I get exception:
envelope_xdr = s.h.transaction('4cab818a57ee33ef84b73888d2f458086316298c903b94f9b7673ca7f086cc49')['envelope_xdr']
ops = TransactionEnvelope.from_xdr(envelope_xdr).tx.operations
<ipython-input-52-b183c322ba18> in <module>()
----> 1 ops = get_operations_from_envelope_xdr(t['envelope_xdr'])
/home/path/proj/proj_package/stellar/utils.pyc in get_operations_from_envelope_xdr(envelope_xdr)
3
4 def get_operations_from_envelope_xdr(envelope_xdr):
----> 5 return TransactionEnvelope.from_xdr(envelope_xdr).tx.operations
/home/path/Envs/env/local/lib/python2.7/site-packages/stellar_base/transaction_envelope.pyc in from_xdr(cls, xdr)
70 signatures = te_xdr_object.signatures
71 tx_xdr_object = te_xdr_object.tx
---> 72 tx = Transaction.from_xdr_object(tx_xdr_object)
73 te = TransactionEnvelope(tx, {'signatures': signatures})
74 # te = TransactionEnvelope(tx, {'signatures': signatures, 'network_id': 'PUBLIC'})
/home/path/Envs/env/local/lib/python2.7/site-packages/stellar_base/transaction.pyc in from_xdr_object(cls, tx_xdr_object)
84 operations.append(AllowTrust.from_xdr_object(op))
85 elif op.type == Xdr.const.SET_OPTIONS:
---> 86 operations.append(SetOptions.from_xdr_object(op))
87 elif op.type == Xdr.const.MANAGE_OFFER:
88 operations.append(ManageOffer.from_xdr_object(op))
/home/path/Envs/env/local/lib/python2.7/site-packages/stellar_base/operation.pyc in from_xdr_object(cls, op_xdr_object)
373
374 if op_xdr_object.body.setOptionsOp.signer:
--> 375 key = op_xdr_object.body.setOptionOp.signer[0].key
376 if key.type == Xdr.const.SIGNER_KEY_TYPE_ED25519:
377 signer_address = encode_check('account', key.ed25519).decode()
AttributeError: 'nullclass' object has no attribute 'setOptionOp'
Is it library bug or I did something wrong?
Library version: stellar-base==0.1.8.1
Python 3.6.5 (default, May 20 2018, 22:12:53)
In [1]: from stellar_base.keypair import Keypair
[...]
In [3]: kp = Keypair.random()
In [4]: kp.public_key().decode()
------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-7-a69f39d344ae> in <module>()
----> 1 kp.public_key().decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xea in position 1: invalid continuation byte
I think I've hit a bug in the Builder code. I have this code:
add_signer_tx = stellar_builder.Builder(secret=issuer_seed, network=args.network)
add_signer_tx.append_set_options_op(master_weight=3, low_threshold=1, med_threshold=3, high_threshold=3)
add_signer_tx.append_set_options_op(signer_address=base_keypair.address().decode(), signer_weight=1)
add_signer_tx.sign()
add_signer_tx.submit()
But it throws the following exception when trying to create the operation for adding the signer_address:
Traceback (most recent call last):
File "/home/jimbob/.virtualenvs/zipzap/lib/python3.5/site-packages/stellar_base/operation.py", line 306, in __init__
decode_check('account', self.signer_address)
NameError: name 'decode_check' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./bin/issue_asset", line 58, in <module>
add_signer_tx.append_set_options_op(signer_address=base_keypair.address(), signer_weight=1)
File "/home/jimbob/.virtualenvs/zipzap/lib/python3.5/site-packages/stellar_base/builder.py", line 149, in append_set_options_op
op = SetOptions(opts)
File "/home/jimbob/.virtualenvs/zipzap/lib/python3.5/site-packages/stellar_base/operation.py", line 307, in __init__
except DecodeError:
NameError: name 'DecodeError' is not defined
Installed via setup.py on ubuntu 15.10
Traceback (most recent call last):
File "./sample.py", line 53, in
operation,
File "build/bdist.linux-x86_64/egg/stellar_base/transaction.py", line 24, in init
AssertionError
AssertionError Traceback (most recent call last)
in ()
7 'fee': 100,
8 'operations': [
----> 9 operation,
10 ],
11 },
/usr/local/lib/python2.7/dist-packages/stellar_base-0.0.1-py2.7.egg/stellar_base/transaction.pyc in init(self, source, opts)
22 assert decode_check('account', source)
23 assert type(opts) is dict
---> 24 assert opts.get('sequence') is not None
25
26 self.source = source
AssertionError:
>>> help(stellar_base.utils.StellarMnemonic)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'stellar_base.utils' has no attribute 'StellarMnemonic'
>>> from stellar_base.utils import StellarMnemonic
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'StellarMnemonic'
I'm attempting to follow the README.md guidance for creating a deterministic keypair and it's not working out so far. :(
Version information follows:
Name: stellar-base
Version: 0.1.5
Summary: Code for managing Stellar.org blockchain transactions and accounts
using stellar-base in python. Allows full functionality interfacing
with the Horizon front end.
Home-page: http://github.com/stellarCN/py-stellar-base/
Author: antb123
Author-email: [email protected]
License: Apache
Location: /home/webusr/.local/lib/python3.6/site-packages
Requires: ed25519, crc16, requests, SSEClient, numpy
There seems to be no obvious way for getting a built transaction hash. What am I missing?
Thanks.
If I set flags like this
SetOptions({
'set_flags': 'AUTH_REQUIRED',
})
In both Python 2.7 and 3.5 I get error
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 20, in sign
tx_hash = self.hash_meta()
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 26, in hash_meta
return xdr_hash(self.signature_base())
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 35, in signature_base
tx.pack_Transaction(self.tx.to_xdr_object())
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1298, in pack_Transaction
self.pack_array(data.operations, self.pack_Operation)
File "/usr/local/lib/python3.5/xdrlib.py", line 128, in pack_array
self.pack_farray(n, list, pack_item)
File "/usr/local/lib/python3.5/xdrlib.py", line 123, in pack_farray
pack_item(item)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1210, in pack_Operation
self.pack_SetOptionsOp(data.body.setOptionsOp)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1094, in pack_SetOptionsOp
raise TypeError( 'data.inflationDest == None')
TypeError: data.inflationDest == None
but when write code
SetOptions({
'inflation_dest': 'GAWROJVDAUIUDHENFINHHPXP3FF3OYD56E7XO3YN74T3A4LAKDMUHBEG',
'set_flags': 'AUTH_REQUIRED',
})
Then in Python3.5 I get error:
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 20, in sign
tx_hash = self.hash_meta()
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 26, in hash_meta
return xdr_hash(self.signature_base())
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 35, in signature_base
tx.pack_Transaction(self.tx.to_xdr_object())
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1298, in pack_Transaction
self.pack_array(data.operations, self.pack_Operation)
File "/usr/local/lib/python3.5/xdrlib.py", line 128, in pack_array
self.pack_farray(n, list, pack_item)
File "/usr/local/lib/python3.5/xdrlib.py", line 123, in pack_farray
pack_item(item)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1210, in pack_Operation
self.pack_SetOptionsOp(data.body.setOptionsOp)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1095, in pack_SetOptionsOp
if len(data.inflationDest) > 1 and self.check_array:
TypeError: object of type 'PublicKey' has no len()
and in Python2.7 I get error
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 20, in sign
tx_hash = self.hash_meta()
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 26, in hash_meta
return xdr_hash(self.signature_base())
File "src/lib/stellar-sdk-py/stellar_base/transaction_envelope.py", line 35, in signature_base
tx.pack_Transaction(self.tx.to_xdr_object())
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1298, in pack_Transaction
self.pack_array(data.operations, self.pack_Operation)
File "/usr/lib/python2.7/xdrlib.py", line 131, in pack_array
self.pack_farray(n, list, pack_item)
File "/usr/lib/python2.7/xdrlib.py", line 126, in pack_farray
pack_item(item)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1210, in pack_Operation
self.pack_SetOptionsOp(data.body.setOptionsOp)
File "src/lib/stellar-sdk-py/stellar_base/stellarxdr/StellarXDR_pack.py", line 1096, in pack_SetOptionsOp
raise XDRError( 'array length too long for data.inflationDest')
xdrlib.Error: array length too long for data.inflationDest
And should I write flag as string? Because I cannot find constants in SDK.
In README.md:
builder = Builder(secret=seed) # or builder = Builder(secret=secret, network='public') for LIVENET.
builder.import_from_xdr(xdr_string) # the xdr_string come from your friend
builder.sign()
builder.to_xdr() # generate new xdr string
# or builder.submit() # submit to Stellar network
builder.to_xdr()
doesn't exist and should be replaced with builder.gen_xdr()
.
Hello,
I tried to send transaction from one account to another.
from stellar_base.builder import Builder
seed = "seed"
builder = Builder(secret=seed, network='public')
bob_address = 'GBSNPTNJFNYOOPKRQE5VQTRVDP7F43RY4Z4OK4CNQWYCOL6QDCHCII57'
builder.append_payment_op(bob_address,'1','XLM')
builder.sign()
builder.submit()
But I got this error: "Exception: have no sequence, maybe not funded?"
next_builder() does not pass the address to the constructor.
The constructor checks for presence of address parameter, and if it is not provided, it raises an exception. This makes it impossible to use next_builder() at the moment
I am referring to this particular check.
Hi, I want to check the signatures on an envelope (basically I hope to get something like an address). I run the code:
envelope.signatures
and it returned me something like:
[DecoratedSignature(hint=b'\xb1.{;', signature=b'\x1b\x03#\xf2\xb2\xa9\xee\xa1n\xa5\xb7\xbd\xa5\x94\x9f\xdcq\xa5\xc5`\xfc-\xf8\xc5\xc7\x84\xd5\x81\x03\x0e\x0c&\xcb\xe8\x85\xfa\xff\xc4\x1f\xbc\xcc\xefr\xd8\xa3\xff\xd9\x8bg\xdb^C]u\xe1\x1ch\xcf\xad\x8a\x9c\xbe\x95\x0c')]
I want to ask how do I decrypt this DecoratedSignature into something that is actually recognisable?
Thank you very much.
Found during a debugging session. Root cause is wrong signer type comparison. Fix in progress.
hI, i have a simple API that make transactions between accounts, we have an Asset and we want to make transactions with it, the problem is that we need to "Allow Trust" every time when we created an account.
We need to allow our asset on automatic when we created and activated the account.
Any idea if in this library we can do this?
Hi, I tried to generate a keypair and got the error below. Could you please take a look? Thanks.
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self.handler)
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject
obj = import(path[0])
File "C:\Users\kunle\Documents\LAGOS_BUSINESS\ISHOPEAZYV2\iShopEazyV2WebApp\ishopeazy.py", line 21, in
from stellar_base.keypair import Keypair
File "C:\Users\kunle\Documents\LAGOS_BUSINESS\ISHOPEAZYV2\iShopEazyV2WebApp\lib\stellar_base\keypair.py", line 7, in
from .utils import XdrLengthError, decode_check, encode_check
File "C:\Users\kunle\Documents\LAGOS_BUSINESS\ISHOPEAZYV2\iShopEazyV2WebApp\lib\stellar_base\utils.py", line 15, in
import ed25519
File "C:\Users\kunle\Documents\LAGOS_BUSINESS\ISHOPEAZYV2\iShopEazyV2WebApp\lib\ed25519_init.py", line 1, in
from .keys import (BadSignatureError, BadPrefixError,
File "C:\Users\kunle\Documents\LAGOS_BUSINESS\ISHOPEAZYV2\iShopEazyV2WebApp\lib\ed25519\keys.py", line 3, in
from . import _ed25519
File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\runtime\sandbox.py", line 1093, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named ed25519._ed25519
Reminder to rewrite tests according to unittests, see discussion in #19 .
When I pass 64 character long utf-8 string as data_name
to manageData
I get error below.
----------------------------------------
Traceback (most recent call last):
...
envelope.sign(keypair=Keypair.from_seed(seed=seed))
File "/home/kalvis/git/sr/py-stellar-base/stellar_base/transaction_envelope.py", line 22, in sign
tx_hash = self.hash_meta()
File "/home/kalvis/git/sr/py-stellar-base/stellar_base/transaction_envelope.py", line 31, in hash_meta
return xdr_hash(self.signature_base())
File "/home/kalvis/git/sr/py-stellar-base/stellar_base/transaction_envelope.py", line 40, in signature_base
tx.pack_Transaction(self.tx.to_xdr_object())
File "/home/kalvis/git/sr/py-stellar-base/stellar_base/stellarxdr/StellarXDR_pack.py", line 728, in pack_Transaction
self.pack_array(data.operations, self.pack_Operation)
File "/usr/lib/python3.4/xdrlib.py", line 111, in pack_array
self.pack_farray(n, list, pack_item)
File "/usr/lib/python3.4/xdrlib.py", line 106, in pack_farray
pack_item(item)
File "/home/kalvis/git/sr/py-stellar-base/stellar_base/stellarxdr/StellarXDR_pack.py", line 654, in pack_Operation
self.pack_ManageDataOp(data.body.manageDataOp)
File "/home/kalvis/git/sr/py-stellar-base/stellar_base/stellarxdr/StellarXDR_pack.py", line 593, in pack_ManageDataOp
self.pack_string64(data.dataName)
File "/home/kalvis/git/sr/py-stellar-base/stellar_base/stellarxdr/StellarXDR_pack.py", line 128, in pack_string64
raise XDRError('array length too long for data')
xdrlib.Error: array length too long for data
----------------------------------------
Adding debug line print(len(data))
in StellarXDR_pack.py
line 127 I learn that at that point string is seen as 67 bytes long and wraps byte string within another byte string like this:
bytearray(b"b\'my64charLongString__________xxxxxxxxxx___________xxxxxxxxxxx____\'")
Hello,
I'm having a hard time figuring out how to recover a seed from a deterministic word list. Using the test wordlist below that was generated using the existing readme.md documentation.
>>> seed_string = "orchard fan alcohol palm jaguar cool invest maple eager foster pencil cluster"
>>> seed_binary = str.encode(seed_string)
>>> kp = Keypair.from_seed(seed_binary)
Traceback (most recent call last):
File "/home/webusr/devel/overcat_mnemonic/lib64/python3.6/site-packages/stellar_base/utils.py", line 118, in decode_check
decoded = base64.b32decode(encoded)
File "/usr/lib64/python3.6/base64.py", line 205, in b32decode
raise binascii.Error('Incorrect padding')
binascii.Error: Incorrect padding
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/webusr/devel/overcat_mnemonic/lib64/python3.6/site-packages/stellar_base/keypair.py", line 48, in from_seed
raw_seed = decode_check("seed", seed)
File "/home/webusr/devel/overcat_mnemonic/lib64/python3.6/site-packages/stellar_base/utils.py", line 120, in decode_check
raise DecodeError('Incorrect padding')
stellar_base.utils.DecodeError: Incorrect padding
I have tried a few different things to get the string/binary conversion to be happy, and I will keep trying, but I figured if anyone around might know how to do it already, if you show me how I'll add that documentation to the readme.
Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.