Skip to content

Commit

Permalink
Merge branch 'release/0.1.24'
Browse files Browse the repository at this point in the history
  • Loading branch information
xeroc committed May 24, 2018
2 parents 6f2f2b8 + fc9491c commit 57aed88
Show file tree
Hide file tree
Showing 4 changed files with 162 additions and 18 deletions.
54 changes: 38 additions & 16 deletions peerplays/transactionbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ class ProposalBuilder:
supposed to expire
:param int proposal_review: Number of seconds for review of the
proposal
:param peerplays.transactionbuilder.TransactionBuilder: Specify
:param .transactionbuilder.TransactionBuilder: Specify
your own instance of transaction builder (optional)
:param peerplays.peerplays.PeerPlays blockchain_instance: PeerPlays
instance
:param instance blockchain_instance: Blockchain instance
"""
def __init__(
self,
Expand Down Expand Up @@ -138,11 +137,18 @@ def __init__(
):
BlockchainInstance.__init__(self, **kwargs)
self.clear()
if not isinstance(tx, dict):
raise ValueError("Invalid TransactionBuilder Format")
super(TransactionBuilder, self).__init__(tx)
# Do we need to reconstruct the tx from self.ops?
self._require_reconstruction = True
if tx and isinstance(tx, dict):
super(TransactionBuilder, self).__init__(tx)
# Load operations
self.ops = tx["operations"]
self._require_reconstruction = False
else:
self._require_reconstruction = True
self.set_expiration(kwargs.get("expiration", 30))
self.set_fee_asset(kwargs.get("fee_asset", "1.3.0"))

def set_expiration(self, p):
self.expiration = p

def is_empty(self):
return not (len(self.ops) > 0)
Expand Down Expand Up @@ -210,6 +216,7 @@ def appendSigner(self, account, permission):
if self.blockchain.wallet.locked():
raise WalletLocked()

# Let's define a helper function for recursion
def fetchkeys(account, perm, level=0):
if level > 2:
return []
Expand All @@ -231,6 +238,7 @@ def fetchkeys(account, perm, level=0):

return r

# Now let's actually deal with the accounts
if account not in self.signing_accounts:
# is the account an instance of public key?
if isinstance(account, PublicKey):
Expand All @@ -239,11 +247,14 @@ def fetchkeys(account, perm, level=0):
str(account)
)
)
# ... or should we rather obtain the keys from an account name
else:
account = Account(account, blockchain_instance=self.blockchain)
required_treshold = account[permission]["weight_threshold"]
keys = fetchkeys(account, permission)
if permission != "owner":
# If we couldn't find an active key, let's try overwrite it
# with an owner key
if not keys and permission != "owner":
keys.extend(fetchkeys(account, "owner"))
for x in keys:
self.wifs.add(x[0])
Expand All @@ -260,6 +271,12 @@ def appendWif(self, wif):
except:
raise InvalidWifError

def set_fee_asset(self, fee_asset):
""" Set asset to fee
"""
# FIXME: this should ensure that fee_asset contains an id
self.fee_asset_id = fee_asset

def constructTx(self):
""" Construct the actual transaction and store it in the class's dict
store
Expand All @@ -276,9 +293,12 @@ def constructTx(self):
# otherwise, we simply wrap ops into Operations
ops.extend([Operation(op)])

# We no wrap everything into an actual transaction
ops = transactions.addRequiredFees(self.blockchain.rpc, ops)
expiration = transactions.formatTimeFromNow(self.blockchain.expiration)
# We now wrap everything into an actual transaction
ops = transactions.addRequiredFees(self.blockchain.rpc, ops,
asset_id=self.fee_asset_id)
expiration = transactions.formatTimeFromNow(
self.expiration or self.blockchain.expiration
)
ref_block_num, ref_block_prefix = transactions.getBlockParams(
self.blockchain.rpc)
self.tx = Signed_Transaction(
Expand All @@ -287,11 +307,11 @@ def constructTx(self):
expiration=expiration,
operations=ops
)
super(TransactionBuilder, self).__init__(self.tx.json())
super(TransactionBuilder, self).update(self.tx.json())
self._unset_require_reconstruction()

def sign(self):
""" Sign a provided transaction witht he provided key(s)
""" Sign a provided transaction with the provided key(s)
:param dict tx: The transaction to be signed and returned
:param string wifs: One or many wif keys to use for signing
Expand Down Expand Up @@ -332,6 +352,7 @@ def sign(self):

signedtx.sign(self.wifs, chain=self.blockchain.rpc.chain_params)
self["signatures"].extend(signedtx.json().get("signatures"))
return signedtx

def verify_authority(self):
""" Verify the authority of the signed transaction
Expand All @@ -343,7 +364,7 @@ def verify_authority(self):
raise e

def broadcast(self):
""" Broadcast a transaction to the PeerPlays network
""" Broadcast a transaction to the blockchain network
:param tx tx: Signed transaction to broadcast
"""
Expand Down Expand Up @@ -372,8 +393,9 @@ def broadcast(self):
ret, api="network_broadcast")
except Exception as e:
raise e
finally:
self.clear()

self.clear()
return ret

def clear(self):
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
ascii = codecs.lookup('ascii')
codecs.register(lambda name, enc=ascii: {True: enc}.get(name == 'mbcs'))

VERSION = '0.1.23'
VERSION = '0.1.24'

setup(
name='peerplays',
Expand Down Expand Up @@ -46,7 +46,7 @@
],
},
install_requires=[
"graphenelib>=0.6.1",
"graphenelib>=0.6.2",
"appdirs",
"prettytable",
"events==0.3",
Expand Down
26 changes: 26 additions & 0 deletions tests/test_cachedlist.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import time
import unittest
from mock import MagicMock
from peerplays import PeerPlays


class Testcases(unittest.TestCase):
pass

"""
def test_proposals(self):
from peerplays.proposal import Proposals
Proposals("witness-account")
Proposals("witness-account")
time.sleep(11)
Proposals("witness-account")
def test_bms(self):
from peerplays.bettingmarket import BettingMarkets
BettingMarkets("1.20.0")
BettingMarkets("1.20.0")
time.sleep(11)
BettingMarkets("1.20.0")
"""
96 changes: 96 additions & 0 deletions tests/test_finalizeOp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import mock
import datetime
import unittest

from mock import MagicMock, PropertyMock
from pprint import pprint

from peerplays import PeerPlays
from peerplays.account import Account
from peerplays.utils import parse_time
from peerplays.instance import set_shared_peerplays_instance
from peerplays.blockchainobject import BlockchainObject, ObjectCache

from peerplaysbase.operationids import getOperationNameForId
from peerplaysbase import operations

wifs = [
"5KR4dZcS2JTeT7eedB8BvFzUesNhjkyxNR7mwXmqVypAogD35ZX",
"5KRKC9N5ZvRBA7TWDbznYVE6gxw7Drjs5A36N1sVPJf12MAXag3",
"5KDQVCFfBMvtc3JEywQPbwiCEvPSzQokJUJPsPUfCayBJVUYVSM"
]

account_id = "1.2.999"
test_operation_dicts = [
{'active': {'account_auths': [],
'address_auths': [],
'key_auths': [['PPY7oA1zCmmK3JWP7uNbJ2Z6Fe8G7fjWos7T6ih2WC3iAvGfMVaYD',
1]],
'weight_threshold': 1},
'active_special_authority': [0, {}],
'blacklisted_accounts': [],
'blacklisting_accounts': [],
'cashback_vb': '1.13.0',
'id': account_id,
'lifetime_referrer': account_id,
'lifetime_referrer_fee_percentage': 8000,
'membership_expiration_date': '1969-12-31T23:59:59',
'name': 'init0',
'network_fee_percentage': 2000,
'options': {'extensions': [],
'memo_key': 'PPY8R3ZAd6AtQDQK9cin6fHEw9uKUwzzxLbo2w6X1aKC5Wtir8iND',
'num_committee': 0,
'num_witness': 0,
'votes': [],
'voting_account': '1.2.5'},
'owner': {'account_auths': [],
'address_auths': [],
'key_auths': [['PPY8Y6f9GoaLnSmLhF8FDSc5YijLddD8ThwdEwGaNGBdCMDD8o7zF',
1]],
'weight_threshold': 1},
'owner_special_authority': [0, {}],
'referrer': '1.2.7',
'referrer_rewards_percentage': 0,
'registrar': '1.2.7',
'statistics': '2.6.7',
'top_n_control_flags': 0,
'whitelisted_accounts': [],
'whitelisting_accounts': []}
]


class Testcases(unittest.TestCase):

def __init__(self, *args, **kwargs):
super(Testcases, self).__init__(*args, **kwargs)
self.ppy = PeerPlays(
nobroadcast=True,
keys=wifs
)
set_shared_peerplays_instance(self.ppy)
self.mockAccount()

def mockAccount(self):
_cache = ObjectCache(default_expiration=60 * 60 * 1, no_overwrite=True)
for i in test_operation_dicts:
_cache[i["id"]] = i
BlockchainObject._cache = _cache

def test_finalize(self):
account = Account(account_id)

op = operations.Transfer(**{
"fee": {
"asset_id": "1.3.0",
"amount": 1
},
"from": account_id,
"to": '1.2.8',
"amount": {
"asset_id": "1.3.0",
"amount": 1
}
})

tx = self.ppy.finalizeOp(op, account, "active")
self.assertEqual(len(tx["signatures"]), 1)

0 comments on commit 57aed88

Please sign in to comment.