Coder Social home page Coder Social logo

neb.py's Introduction

neb.py

neb.py is the Nebulas compatible Python API. Users can sign/send transactions and deploy/call smart contract with it.

Installation

You can install this library via pip:

pip install neb-py

Usage

please refer to examples to learn how to use neb.py.

Account

from nebpysdk.src.account.Account import Account
# generate a new account
account = Account()
account2 = Account.new_account() #another way to create account
priv_key = "6c41a31b4e689e1441c930ce4c34b74cc037bd5e68bbd6878adb2facf62aa7f3"
account3 = Account(priv_key) #create account with given priv_key

# export account
account_json = account.to_key(bytes("passphrase".encode()))
print(account_json)

# load account
account = Account.from_key(account_json, bytes("passphrase".encode()))
print(account.get_address_str())
print(account.get_private_key())
print(account.get_public_key())

API

from nebpysdk.src.client.Neb import Neb
import json
neb = Neb("https://testnet.nebulas.io")

# getNebState
print(neb.api.getNebState().text)

# latestIrreversibleBlock
print(neb.api.latestIrreversibleBlock().text)

Transaction

from nebpysdk.src.account.Account import Account
from nebpysdk.src.core.Address import Address
from nebpysdk.src.core.Transaction import Transaction
from nebpysdk.src.core.TransactionBinaryPayload import TransactionBinaryPayload
from nebpysdk.src.core.TransactionCallPayload import TransactionCallPayload
from nebpysdk.src.client.Neb import Neb
import json

neb = Neb("https://testnet.nebulas.io")
keyJson = '{"version":4,"id":"814745d0-9200-42bd-a4df-557b2d7e1d8b","address":"n1H2Yb5Q6ZfKvs61htVSV4b1U2gr2GA9vo6","crypto":{"ciphertext":"fb831107ce71ed9064fca0de8d514d7b2ba0aa03aa4fa6302d09fdfdfad23a18","cipherparams":{"iv":"fb65caf32f4dbb2593e36b02c07b8484"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"dklen":32,"salt":"dddc4f9b3e2079b5cc65d82d4f9ecf27da6ec86770cb627a19bc76d094bf9472","n":4096,"r":8,"p":1},"mac":"1a66d8e18d10404440d2762c0d59d0ce9e12a4bbdfc03323736a435a0761ee23","machash":"sha3256"}}';
password = 'passphrase'

# prepare from&to addr
from_account = Account.from_key(keyJson, bytes(password.encode()))
from_addr = from_account.get_address_obj()
to_addr = Address.parse_from_string("n1JmhE82GNjdZPNZr6dgUuSfzy2WRwmD9zy")
print("from_addr", from_addr.string())
print("to_addr  ", to_addr.string())

# prepare transaction, get nonce first
resp = neb.api.getAccountState(from_addr.string()).text

print(resp)
resp_json = json.loads(resp)
print(resp_json)
nonce = int(resp_json['result']['nonce'])

chain_id = 1001
# PayloadType
payload_type = Transaction.PayloadType("binary")
# payload
payload = TransactionBinaryPayload("test").to_bytes()
# gasPrice
gas_price = 1000000
# gasLimit
gas_limit = 20000

# binary transaction example
tx = Transaction(chain_id, from_account, to_addr, 0, nonce + 1, payload_type, payload, gas_price, gas_limit)
tx.calculate_hash()
tx.sign_hash()
print(neb.api.sendRawTransaction(tx.to_proto()).text)


# call type
to_addr = Address.parse_from_string("n1oXdmwuo5jJRExnZR5rbceMEyzRsPeALgm")
func = "get"
arg = '["nebulas"]'
payload = TransactionCallPayload(func, arg).to_bytes()
payload_type = Transaction.PayloadType("call")
tx = Transaction(chain_id, from_account, to_addr, 0, nonce + 1, payload_type, payload, gas_price, gas_limit)
tx.calculate_hash()
tx.sign_hash()
print(neb.api.sendRawTransaction(tx.to_proto()).text)

Join in!

We are happy to receive bug reports, fixes, documentation enhancements, and other improvements.

Please report bugs via the github issue

neb.py's People

Contributors

includeleec avatar yupnano avatar zzzzking avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

neb.py's Issues

how to pass the args ,when i call function of smart contract?

i make a transaction using class Transaction, when i'd like to call a function in contract.
the payload is make by class TransactionCallPayload(), its init function is [def init(self, _function, args)], the question is i don't know how to make the "args".
the args i'd like to pass is ["{\"name\":\"myname\"}"] (i typed this to web-wallet, and it works)
so i code below:
name = "myname"
arg = []
param = {
"name":name,
}
arg.append(json.dumps(param)) #i try arg.append(param), but it shows error too.

but is don't work, the blockchain show :
TxReceipt Status: | fail ( invalid argument(s) )

i tried again and again using difference code...

finally, i code below:
arg = '["{\\\"name\\\":\\\"%s\\\"}"]' % (name)
it works unexpectedly, but it is so ugly, there must be something wrong, i think.

help me please!

could not install neb through pip install neb-py

this is the log,and i have no ideal about what is wrong because i am a python beginner.
maybe eth-hash has wrong,i can install eth-hash0.1.4, but the neb-py use eth-hash0.1.3, i could not install this。(i use python2.7 on win10)


Collecting neb-py
  Using cached https://files.pythonhosted.org/packages/d5/ec/3ac26ea9319ab3bb6a77dd3bbbe1044111f9a94d0ab3c2f72b70ae83e8e2/neb-py-0.4.1.tar.gz
Collecting certifi==2018.4.16 (from neb-py)
  Using cached https://files.pythonhosted.org/packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl
Requirement already satisfied: chardet==3.0.4 in c:\python27\lib\site-packages (from neb-py) (3.0.4)
Collecting Crypto==1.4.1 (from neb-py)
  Using cached https://files.pythonhosted.org/packages/fc/bb/0b812dc02e6357606228edfbf5808f5ca0a675a84273578c3a199e841cd8/crypto-1.4.1-py2.py3-none-any.whl
Collecting cytoolz==0.9.0.1 (from neb-py)
  Using cached https://files.pythonhosted.org/packages/36/f4/9728ba01ccb2f55df9a5af029b48ba0aaca1081bbd7823ea2ee223ba7a42/cytoolz-0.9.0.1.tar.gz
Collecting eth-hash==0.1.3 (from neb-py)
  Using cached https://files.pythonhosted.org/packages/db/ce/16293ee4ed1ccc5de265e11f7ecd21ba054cdeb9f601bde50eb72c1aac62/eth-hash-0.1.3.tar.gz
    Complete output from command python setup.py egg_info:

    Installed c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs\setuptools_markdown-0.2-py2.7.egg
    Searching for pypandoc
    Reading https://pypi.python.org/simple/pypandoc/
    Best match: pypandoc 1.4
    Downloading https://files.pythonhosted.org/packages/71/81/00184643e5a10a456b4118fc12c96780823adb8ed974eb2289f29703b29b/pypandoc-1.4.tar.gz#sha256=e914e6d5f84a76764887e4d909b09d63308725f0cbb5293872c2c92f07c11a5b
    Processing pypandoc-1.4.tar.gz
    Writing c:\users\lenovo\appdata\local\temp\easy_install-0zuffb\pypandoc-1.4\setup.cfg
    Running pypandoc-1.4\setup.py -q bdist_egg --dist-dir c:\users\lenovo\appdata\local\temp\easy_install-0zuffb\pypandoc-1.4\egg-dist-tmp-hmsuig
    See http://johnmacfarlane.net/pandoc/installing.html
    for installation options
    ---------------------------------------------------------------

    **zip_safe flag not set; analyzing archive contents...
    pypandoc.__init__: module references __file__


    !!! pandoc not found, long_description is bad, don't upload this to PyPI !!!**


    creating c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs\pypandoc-1.4-py2.7.egg
    Extracting pypandoc-1.4-py2.7.egg to c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs

    Installed c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs\pypandoc-1.4-py2.7.egg
    Searching for wheel>=0.25.0
    Reading https://pypi.python.org/simple/wheel/
    Best match: wheel 0.31.1
    Downloading https://files.pythonhosted.org/packages/2a/fb/aefe5d5dbc3f4fe1e815bcdb05cbaab19744d201bbc9b59cfa06ec7fc789/wheel-0.31.1.tar.gz#sha256=0a2e54558a0628f2145d2fc822137e322412115173e8a2ddbe1c9024338ae83c
    Processing wheel-0.31.1.tar.gz
    Writing c:\users\lenovo\appdata\local\temp\easy_install-tlceal\wheel-0.31.1\setup.cfg
    Running wheel-0.31.1\setup.py -q bdist_egg --dist-dir c:\users\lenovo\appdata\local\temp\easy_install-tlceal\wheel-0.31.1\egg-dist-tmp-mvh4do
    c:\python27\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'python_requires'
      warnings.warn(msg)
    **warning: no files found matching 'wheel\*.txt'**
   ** warning: no files found matching '*.sh'**
    **warning: no files found matching '*.py' under directory 'wheel\test'**
    **warning: no files found matching 'wheel\test\test-1.0-py2.py3-none-win32.whl'**
   ** warning: no files found matching 'wheel\test\headers.dist\header.h'
    warning: no files found matching 'wheel\test\pydist-schema.json'
    no previously-included directories found matching 'wheel\test\*\dist'
    no previously-included directories found matching 'wheel\test\*\build'**
    creating c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs\wheel-0.31.1-py2.7.egg
    Extracting wheel-0.31.1-py2.7.egg to c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs

    Installed c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs\wheel-0.31.1-py2.7.egg
    c:\python27\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'python_requires'
      warnings.warn(msg)
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\setup.py", line 72, in <module>
        'Programming Language :: Python :: Implementation :: PyPy',
      File "c:\python27\lib\distutils\core.py", line 111, in setup
        _setup_distribution = dist = klass(attrs)
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 272, in __init__
        _Distribution.__init__(self,attrs)
      File "c:\python27\lib\distutils\dist.py", line 287, in __init__
        self.finalize_options()
      File "c:\python27\lib\site-packages\setuptools\dist.py", line 327, in finalize_options
        ep.load()(self, ep.name, value)
      File "c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs\setuptools_markdown-0.2-py2.7.egg\setuptools_markdown.py", line 22, in long_description_markdown_filename
        output = pypandoc.convert(markdown_filename, 'rst')
      File "c:\users\lenovo\appdata\local\temp\pip-install-wm6abh\eth-hash\.eggs\pypandoc-1.4-py2.7.egg\pypandoc\__init__.py", line 66, in convert
        raise RuntimeError("Format missing, but need one (identified source as text as no "
    **RuntimeError: Format missing, but need one (identified source as text as no file with that name was found).**

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\xxx\appdata\local\temp\pip-install-wm6abh\eth-hash\

what's wrong?

{"result":{"balance":"0","nonce":"0","type":87}}
{'result': {'type': 87, 'nonce': '0', 'balance': '0'}}
{"error":"cannot found contract account in storage please check contract address is valid or deploy is success"}

'module' object has no attribute 'sha3_256'

Traceback (most recent call last):
File "tmp.py", line 18, in
account = Account.new_account()
File "/usr/local/lib/python3.4/dist-packages/nebpysdk/src/account/Account.py", line 33, in new_account
return Account(private_key)
File "/usr/local/lib/python3.4/dist-packages/nebpysdk/src/account/Account.py", line 23, in init
self.__address = Address.new_address_from_pub_key(self.__publickey.encode())
File "/usr/local/lib/python3.4/dist-packages/nebpysdk/src/core/Address.py", line 105, in new_address_from_pub_key
return cls.new_address(cls.AddressType.ACCOUNT, pub)
File "/usr/local/lib/python3.4/dist-packages/nebpysdk/src/core/Address.py", line 81, in new_address
sha3_256_value = hashlib.sha3_256()
AttributeError: 'module' object has no attribute 'sha3_256'

can't run account

python3 mac os
from Crypto.Hash import SHA3_256 as SHA3
ImportError: cannot import name 'SHA3_256'

for Python3.7 requirement.txt(success)

python version: 3.7

beautifulsoup4==4.7.1
cachetools==3.1.0
certifi==2018.11.29
chardet==3.0.4
crypto==1.4.1
cytoolz==0.9.0.1
eth-hash==0.2.0
eth-keys==0.2.1
eth-typing==2.0.0
eth-utils==1.4.1
google==2.0.1
google-api-python-client==1.7.8
google-auth==1.6.3
google-auth-httplib2==0.0.3
httplib2==0.12.1
idna==2.8
Naked==0.1.31
protobuf==3.7.0
pyasn1==0.4.5
pyasn1-modules==0.2.4
pycryptodome==3.7.3
pyscrypt==1.6.2
PyYAML==3.13
requests==2.21.0
rsa==4.0
shellescape==3.4.1
six==1.12.0
soupsieve==1.8
toolz==0.9.0
uritemplate==3.0.0
urllib3==1.24.1

the call function is incorrect

the param type of function call(self, from_addr: str, to_addr: str, value: int, nonce: int, gasprice: int, gaslimit: int, contract=None) in class Api is incorrect.
the value must be string
the gasprice、geslimit must be string
otherwise, i will get error:
{"error":"json: cannot unmarshal number into Go value of type string"}

and the example is right in ApiExample.py
re = neb.api.call("n1JmhE82GNjdZPNZr6dgUuSfzy2WRwmD9zy",
"n1zRenwNRXVwY6akcF4rUNoKhmNWP9bhSq8",
"100000",
int(re['result']['nonce']) + 1,
"200000",
"200000", {'function': 'getOrderCount', 'args': ''}).text

Address.py 中校验地址”校验和“部分代码是否存在逻辑Bug?

(https://github.com/nebulasio/neb.py/blob/master/nebpysdk/src/core/Address.py#L125)

@classmethod
    def parse_from_bytes(cls, byte):
        if len(byte) != cls.__AddressLength or byte[0] != cls.__PaddingByte[0]:
            raise Exception("invalid address bytes")
        checksum = byte[cls.__AddressLength - cls.__AddressChecksumLength:] 
        checkdata = byte[:cls.__AddressLength - cls.__AddressChecksumLength]
        if not cls.byte_equal(cls.check_sum(checkdata), checksum):
            raise Exception("invalid address check sum")
        return Address(byte)

@ideaalloc

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.