Sylvain Bellemare 50b0b3cef2 Rebase/feat/586/integrate tx model (#641)
* Adjust imports to bigchaindb_common

* Adjust get_spent function signature

* Adjust block serialization

* Fix BigchainApi Test

* Fix TestTransactionValidation tests

* Fix TestBlockValidation tests

* WIP: TestMultipleInputs

* Adjust tests to tx-model interface changes

- Fix old tests
- Fix tests in TestMultipleInputs class

* Remove fulfillment message tests

* Fix TransactionMalleability tests

* Remove Cryptoconditions tests

* Remove create_transaction

* Remove signing logic

* Remove consensus plugin

* Fix block_creation pipeline

* Fix election pipeline

* Replace some util functions with bdb_common ones

- timestamp ==> gen_timestamp
- serialize.

* Implement Block model

* Simplify function signatures for vote functions

Change parameter interface for the following functions:

- has_previous_vote
- verify_vote_signature
- block_election_status

so that they take a block's id and voters instead of a fake block.

* Integrate Block and Transaction model

* Fix leftover tests and cleanup conftest

* Add bigchaindb-common to install_requires

* Delete transactions after block is written (#609)

* delete transactions after block is written

* cleanup transaction_exists

* check for duplicate transactions

* delete invalid tx from backlog

* test duplicate transaction

* Remove dead code

* Test processes.py

* Test invalid tx in on server

* Fix tests for core.py

* Fix models tests

* Test commands main fn

* Add final coverage to vote pipeline

* Add more tests to voting pipeline

* Remove consensus plugin docs and misc

* Post rebase fixes

* Fix rebase mess

* Remove extra blank line

* Improve docstring

* Remove comment

handled in bigchaindb/cryptoconditions#27;
see https://github.com/bigchaindb/cryptoconditions/issues/27

* Fix block serialization in block creation

* Add signed_ prefix to transfer_tx

* Improve docs

* Add library documentation page on pipelines

* PR feedback for models.py

* Impr. readability of get_last_voted_block

* Use dict comprehension

* Add docker-compose file to build and serve docs

locally for development purposes

* Change private_key for signing_key

* Improve docstrings

* Remove consensus docs

* Document new consensus module

* Create different transactions for the block

* Cleanup variable names in block.py

* Create different transactions for the block

* Cleanup variable names in block.py
2016-09-29 10:29:41 +02:00

174 lines
5.8 KiB
Python

"""This module takes care of all the logic related to block voting.
The logic is encapsulated in the ``Vote`` class, while the sequence
of actions to do on transactions is specified in the ``create_pipeline``
function.
"""
from collections import Counter
from multipipes import Pipeline, Node
from bigchaindb_common import exceptions
from bigchaindb.consensus import BaseConsensusRules
from bigchaindb.models import Transaction, Block
from bigchaindb.pipelines.utils import ChangeFeed
from bigchaindb import Bigchain
class Vote:
"""This class encapsulates the logic to vote on blocks.
Note:
Methods of this class will be executed in different processes.
"""
def __init__(self):
"""Initialize the Block voter."""
# Since cannot share a connection to RethinkDB using multiprocessing,
# we need to create a temporary instance of BigchainDB that we use
# only to query RethinkDB
self.consensus = BaseConsensusRules
# This is the Bigchain instance that will be "shared" (aka: copied)
# by all the subprocesses
self.bigchain = Bigchain()
self.last_voted_id = Bigchain().get_last_voted_block().id
self.counters = Counter()
self.validity = {}
self.invalid_dummy_tx = Transaction.create([self.bigchain.me],
[self.bigchain.me])
def validate_block(self, block):
if not self.bigchain.has_previous_vote(block['id'], block['block']['voters']):
try:
block = Block.from_dict(block)
except (exceptions.InvalidHash, exceptions.InvalidSignature):
# XXX: if a block is invalid we should skip the `validate_tx`
# step, but since we are in a pipeline we cannot just jump to
# another function. Hackish solution: generate an invalid
# transaction and propagate it to the next steps of the
# pipeline.
return block['id'], [self.invalid_dummy_tx]
try:
self.consensus.validate_block(self.bigchain, block)
except (exceptions.InvalidHash,
exceptions.OperationError,
exceptions.InvalidSignature):
# XXX: if a block is invalid we should skip the `validate_tx`
# step, but since we are in a pipeline we cannot just jump to
# another function. Hackish solution: generate an invalid
# transaction and propagate it to the next steps of the
# pipeline.
return block.id, [self.invalid_dummy_tx]
return block.id, block.transactions
def ungroup(self, block_id, transactions):
"""Given a block, ungroup the transactions in it.
Args:
block_id (str): the id of the block in progress.
transactions (list(Transaction)): transactions of the block in
progress.
Returns:
``None`` if the block has been already voted, an iterator that
yields a transaction, block id, and the total number of
transactions contained in the block otherwise.
"""
num_tx = len(transactions)
for tx in transactions:
yield tx, block_id, num_tx
def validate_tx(self, tx, block_id, num_tx):
"""Validate a transaction.
Args:
tx (dict): the transaction to validate
block_id (str): the id of block containing the transaction
num_tx (int): the total number of transactions to process
Returns:
Three values are returned, the validity of the transaction,
``block_id``, ``num_tx``.
"""
return bool(self.bigchain.is_valid_transaction(tx)), block_id, num_tx
def vote(self, tx_validity, block_id, num_tx):
"""Collect the validity of transactions and cast a vote when ready.
Args:
tx_validity (bool): the validity of the transaction
block_id (str): the id of block containing the transaction
num_tx (int): the total number of transactions to process
Returns:
None, or a vote if a decision has been reached.
"""
self.counters[block_id] += 1
self.validity[block_id] = tx_validity and self.validity.get(block_id,
True)
if self.counters[block_id] == num_tx:
vote = self.bigchain.vote(block_id,
self.last_voted_id,
self.validity[block_id])
self.last_voted_id = block_id
del self.counters[block_id]
del self.validity[block_id]
return vote
def write_vote(self, vote):
"""Write vote to the database.
Args:
vote: the vote to write.
"""
self.bigchain.write_vote(vote)
return vote
def initial():
"""Return unvoted blocks."""
b = Bigchain()
rs = b.get_unvoted_blocks()
return rs
def get_changefeed():
"""Create and return the changefeed for the bigchain table."""
return ChangeFeed('bigchain', operation=ChangeFeed.INSERT, prefeed=initial())
def create_pipeline():
"""Create and return the pipeline of operations to be distributed
on different processes."""
voter = Vote()
vote_pipeline = Pipeline([
Node(voter.validate_block),
Node(voter.ungroup),
Node(voter.validate_tx, fraction_of_cores=1),
Node(voter.vote),
Node(voter.write_vote)
])
return vote_pipeline
def start():
"""Create, start, and return the block pipeline."""
pipeline = create_pipeline()
pipeline.setup(indata=get_changefeed())
pipeline.start()
return pipeline