Commit Graph

38 Commits

Author SHA1 Message Date
Za Wilcox 3bef54b764
change(consensus): Refactor production code for network consensus rules to `Network` methods (#8340)
* begin refactor suggested as "step 2": https://github.com/ZcashFoundation/zebra/issues/7968#issue-2003245309
Squashed from multiple commits to enable partial rebase

* break out more little traits

* add activation implementation leveraging From<Network> for lrz::cons::

* for transfer of ownership I cannot return a type that's owned by the method

* hrp_sapling_extended_full_viewing_key

* complete implementation of interface of Parameters on Network reuse Parameters on zcash Network where possible

* move doc-comments to trait declarations (from impls)

* Simplify/complete Parameters impl for Network

* Add checkpoint_list method, move documentation, etc

* move last match network to inside network method

* add back comment

* use zcash_address for parameter types in zebra-chain

* use inherent methods instead of big parameters passthrough

* revert to implementation of From on zcash_primitives::..::Network vs &zcash_prim...

* move match

* add test to block maximum time rule

* update changelog

* finish porting target_difficutly_limit

* remove obscelete code comment

* revert non-functional change

* finish migrating target_difficulty_limit, checkpoint_list

* update changelog

---------

Co-authored-by: Hazel OHearn <gygaxis@zingolabs.org>
2024-03-12 21:41:44 +00:00
Marek 7c6a0f8388
change(scan): Refactor scanning tests (#8047)
* Derive & impl helper traits from `std`

* Create `compact_to_v4` fn

* Create `fake_block` fn

* Refactor existing tests to use the new functions

* Cosmetics

* Refactor docs

* Put `Default` behind `cfg_attr(test)`

Rationale
---------

We avoid implementing `Default` on consensus-critical types because it's
easy to miss an incorrect use in a review. It's easy to hide a
`default()` in a call like `unwrap_or_default()` or even more subtle
methods.

---------

Co-authored-by: teor <teor@riseup.net>
2023-12-06 01:57:01 +00:00
teor 758eb6e0ea
fix(rpc): Fix bugs and performance of `getnetworksolps` & `getnetworkhashps` RPCs (#7647)
* Handle negative and zero getnetworksolsps arguments correctly

* Simplify the solsps loop structure

* Simplify loop by avoiding manual iteration and peeking

* Avoid division by zero

* Use min and max times rather than first and last times

* Refactor block iterators so they are more efficient

* Make finding chains easier

* Simplify block iteration code

* Remove implemented TODO comments

* Simplify internal iterator state

* Implement iteration by any chain item

* Iterate block headers rather than full blocks

* Ignore code that is (sometimes) dead

* Fix a dead code warning

* Add a no blocks in state error constant

* Check result values in the RPC test

* Fix invalid calculation handling
2023-10-11 02:02:51 +00:00
teor 166526a088
feat(ui): Add a terminal-based progress bar to Zebra (#6235)
* Implement Display and to_string() for NetworkUpgrade

* Add a progress-bar feature to zebrad

* Add the progress bar writer to the tracing component

* Add a block progress bar transmitter

* Correctly shut down the progress bar, and shut it down on an interrupt

* Make it clearer that the progress task never exits

* Add a config for writing logs to a file

* Add a progress-bar feature to zebra-network

* Add a progress bar for the address book size

* Add progress bars for never attempted and failed peers

* Add an optional limit and label to connection counters

* Add open connection progress bars

* Improve CheckpointList API and CheckpointVerifier debugging

* Add checkpoint index and checkpoint queue progress bars

* Security: Limit the number of non-finalized chains tracked by Zebra

* Make some NonFinalizedState methods available with proptest-impl

* Add a non-finalized chain count progress bar

* Track the last fork height for newly forked chains

* Add a should_count_metrics to Chain

* Add a display method for PartialCumulativeWork

* Add a progress bar for each chain fork

* Add a NonFinalizedState::disable_metrics() method and switch to using it

* Move metrics out of Chain because we can't update Arc<Chain>

* Fix: consistently use best chain order when searching chains

* Track Chain progress bars in NonFinalizedState

* Display work as bits, not a multiple of the target difficulty

* Handle negative fork lengths by reporting "No fork"

* Correctly disable unused fork bars

* clippy: rewrite using `match _.cmp(_) { ... }`

* Initial mempool progress bar implementation

* Update Cargo.lock

* Add the actual transaction size as a description to the cost bar

* Only show mempool progress bars after first activation

* Add queued and rejected mempool progress bars

* Clarify cost note is actual size

* Add tracing.log_file config and progress-bar feature to zebrad docs

* Derive Clone for Chain

* Upgrade to howudoin 0.1.2 and remove some bug workarounds

* Directly call the debug formatter to Display a Network

Co-authored-by: Arya <aryasolhi@gmail.com>

* Rename the address count metric to num_addresses

Co-authored-by: Arya <aryasolhi@gmail.com>

* Simplify reverse checkpoint lookup

Co-authored-by: Arya <aryasolhi@gmail.com>

* Simplify progress bar shutdown code

Co-authored-by: Arya <aryasolhi@gmail.com>

* Remove unused MIN_TRANSPARENT_TX_MEMPOOL_SIZE

* Document that the progress task runs forever

* Fix progress log formatting

* If progress-bar is on, log to a file by default

* Create missing directories for log files

* Add file security docs for running Zebra with elevated permissions

* Document automatic log file, spell progress-bar correctly

---------

Co-authored-by: Arya <aryasolhi@gmail.com>
2023-04-13 08:42:17 +00:00
teor 4f289299fd
change(rpc): Simplify `getdifficulty` RPC implementation (#6105)
* Use existing Work type to calculate get_difficulty RPC, round in f64 tests

* Use a valid difficulty in all snapshots

* Explain compatibility TODO

* Fix typo

* Document consensus rules in the difficulty module

* Calculate the difficulty using the high 128 bits of the U256 values

* Require 6 significant figures of accuracy in the difficulty unit tests

* fixup! Calculate the difficulty using the high 128 bits of the U256 values

* Update snapshots
2023-02-08 23:41:41 +00:00
teor e9d6e975b4
change(rpc): Refactor get block template RPC into stages (#5837)
* Add some TODOs

* Move and rename height_from_signed_int()

* Move get_block_template() support functions to a submodule

* Fix incorrect P2SH comments and logs

* Split initial checks into their own functions

* Split state fetch into its own function, do some cleanup

* Move get_block_template_opts to get_block_template::parameters

* Fix and simplify test imports

* Rename block_height to next_block_height

* Rename to chain_tip_and_local_time to make it clear what it contains

* Split fetching mempool transactions out, include them in long poll id

* Refactor coinbase generation

* Split default root calculation into a separate function

* Use DateTime32 for getblocktemplate times

* Use typed difficulty fields rather than strings

* Split out a generate coinbase and roots function

* Move GetBlockTemplate construction into a method

* Document what happens to unusual difficulty values

* Clean up some TODOs

* fastmod check_address check_miner_address

* cargo fmt --all

* Fix an incorrect panic message

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-13 21:25:04 +00:00
Arya 77b85cf767
change(rpc): Adds `getmininginfo`, `getnetworksolps` and `getnetworkhashps` methods (#5808)
* adds type and stub

* adds:
- SolutionRate state request

- getnetworksolps, getnetworkhashps, & getmininginfo RPCs

- vectors tests

* adds snapshot tests

updates ReadRequest::SolutionRate doc link

* removes random slash in doc comment

moves snapshot tests up where it can use the populated state service

* adds snapshots

* updates doc comments

* applies `num_blocks` default in RPC instead of `solution_rate`

* adds # Correctness comment

* Add testnet field to getmininginfo response

* use PartialCumulativeWork instead of u128

* document why `solution_rate` takes an extra block

* add comment explaining why the work for the last block in the iterator is not added to `total_work`

* use `as_u128` method instead of deref for PartialCumulativeWork

* Updates `chain` field of getmininginfo response

* Updates snapshots

Adds "arbitrary_precision" feature to serde_json in zebra-rpc
2022-12-08 19:56:14 +00:00
teor 09836d2800
fix(clippy): Put Rust format variables inline (#5783)
* cargo clippy --fix --all-features --all-targets

With rustc 1.67.0-nightly (234151769 2022-12-03)

* cargo fmt --all
2022-12-08 01:05:57 +00:00
Alfredo Garcia eb66f4b1a3
feat(rpc): populate some getblocktemplate RPC block header fields using the state best chain tip (#5659)
* populate block height

* populate cur_time

* populate min_time

* populate capabilities

* populate last_block_hash

* create read state request for getblocktemplate

* refactor to get difficulty fields more properly

* populate bits and target fields

* fix tests

* add target and bits documentation

* docs

* fix docs

* docs

* remove metrixs counter calls

* apply some suggestions from code review

* hide some code behind feature

* simplify the service

* fix error handling

* remove comment

* fox doc

* panic if we dont have enough state

* bring tip data from the state

* make proposal empty

* fix time

* fix docs, consensus rules

* remove non used anymore fn

* remove another non used fn

* remove no needed change

* remove more unused changes

* remove unused anymore change

* apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

* fix build and snapshots

* apply testnet consensus rule

* fix test

* rustfmt

* remove time as allowed field to be modified by the miner if mining minimum difficulty block

* move all times to before calculating difficulty

* do some cleanup

* Adjust times so the whole time range is a testnet minimum difficulty block

* Return a GetBlockTemplateChainInfo struct from the difficulty calculation

* Add a Zebra-only max_time field to the getblocktemplate RPC

Co-authored-by: teor <teor@riseup.net>
2022-11-28 09:06:32 +00:00
teor 66ea40f215
Resolve unnecessary borrow lint and remove redundant imports (#5045)
```sh
cargo clippy --fix --all-features --all-targets
```
2022-09-02 18:20:32 +00:00
Alfredo Garcia 97fb85dca9
lint(clippy): add `unwrap_in_result` lint (#4667)
* `unwrap_in_result` in zebra-chain crate

* `unwrap_in_result` in zebra-script crate

* `unwrap_in_result` in zebra-state crate

* `unwrap_in_result` in zebra-consensus crate

* `unwrap_in_result` in zebra-test crate

* `unwrap_in_result` in zebra-network crate

* `unwrap_in_result` in zebra-rpc crate

* `unwrap_in_result` in zebrad crate

* rustfmt

* revert `?` and add exceptions

* explain some panics better

* move some lint positions

* replace a panic with error

* Fix rustfmt?

Co-authored-by: teor <teor@riseup.net>
2022-06-28 06:22:07 +00:00
teor 4f0d7bd737
lint: add extra integer lints, and partially fix some code (#3409)
* lint: enable more clippy checks for bug-prone code

* fix(lint): stop denying lints, to avoid being excluded from Crater

Also categorise lints.

* lint: add some lints to the TODO list

* refactor(arithmetic): partial fixes for some integer arithmetic lints

* Document some weird lint behaviour
2022-01-27 11:34:15 -03:00
Conrado Gouvea c9e93a75f7
Replace primitives_types with uint (#2350) 2021-06-18 15:35:05 -03:00
teor 2f0f379a9e
Standardise clippy lints and require docs (#2238)
* Standardise lints across Zebra crates, and add missing docs

The only remaining module with missing docs is `zebra_test::command`

* Todo -> TODO

* Clarify what a transcript ErrorChecker does

Also change `Error` -> `BoxError`

* TransError -> ExpectedTranscriptError

* Output Descriptions -> Output descriptions
2021-06-04 08:48:40 +10:00
teor e8e6d292c5 clippy: make to_* methods take self by value 2021-04-13 23:36:23 -04:00
Alfredo Garcia 21dbf5cb69
fix rust beta panic string warnings (#1731) 2021-02-15 07:00:02 +10:00
teor 66e300be0a
Cleanup the ExpandedDifficulty PartialOrd impl (#1466) 2020-12-14 11:25:50 +10:00
teor 9bd3b8becd Clarify a difficulty debug impl comment 2020-12-04 10:44:36 +10:00
teor 2014dffd27 Show expanded values in CompactDifficulty debug fmt 2020-12-04 10:44:36 +10:00
teor bb9c4918bf Implement threshold_bits 2020-12-01 07:27:30 +10:00
teor 741c44cd55 Implement mean_target_difficulty
And enough stub code to actually run it on the context.
2020-12-01 07:27:30 +10:00
Jane Lusby a5861e5ad9 use arbitrary for creating work 2020-11-12 09:14:52 -05:00
Jane Lusby b287ea58c2 Add proptest for work roundtrip 2020-11-12 09:14:52 -05:00
Jane Lusby 1bc833dbcc Move work conversion helpers to test code 2020-11-12 09:14:52 -05:00
Jane Lusby c41a7303fa Add helpers for setting work on fake chains 2020-11-12 09:14:52 -05:00
teor b2a9ea62fe Round-trip the PoWLimit through the compact representation
`zcashd` converts the PoWLimit into a compact representation before
using it to perform difficulty filter checks.

The Zcash specification converts to compact for the default difficulty
filter, but not for testnet minimum difficulty blocks. (ZIP 205 and
ZIP 208 don't specify this conversion either.) See #1277.
2020-11-12 12:30:54 +10:00
teor 8f838166a8 Make ExpandedDifficulty Debug byte order match Hash
Bugfix on PR #1171.
2020-11-12 12:30:54 +10:00
teor 1c31225aac
Implement Expanded to Compact Difficulty Conversion (#1196)
* Implement Expanded to Compact Difficulty
* Implement Arbitrary for CompactDifficulty
Remove the derive, and generate values from random block
hashes.
* Implement Arbitrary for ExpandedDifficulty and Work
* Use Arbitrary for CompactDifficulty in Arbitrary for Block
* Test difficulty on all block test vectors
And cleanup some duplicate test code
* Round-trip tests for compact test cases
* Round-trip tests for compact difficulty in block test vectors
* Make Add for Work return PartialCumulativeWork
Remove AddAssign for Work
Rewrite a proptest using Sub for PartialCumulativeWork
Use Arbitrary for Work
* Add roundtrip work sum tests
* Add roundtrip comparison difficulty tests
* Add failing proptest cases due to test bugs
* Use Some(_) rather than _.into()
* Reduce visibility of difficulty type inner values
* Split work and other difficulty proptests
This change makes sure that rejected work values don't disable property
tests on other types.
2020-10-30 11:36:59 +10:00
Alfredo Garcia bcb027ebc5 change canopy.pdf to stable protocol.pdf 2020-10-28 11:34:53 -04:00
teor efb9bfa5de
Merge pull request #1165 from teor2345/difficulty-tidy
Tidy some difficulty code
2020-10-16 06:50:08 +10:00
teor c3a8fd3894 Check PoWLimit for difficulty threshold 2020-10-15 08:31:18 +10:00
teor 00de709dd8 impl From<U256> for ExpandedDifficulty 2020-10-15 08:31:18 +10:00
Jane Lusby 86ed13060f
Add tests for `Chain` implementation (#1093)
* Begin work on RFC5 implementation

* I think this is necessary

* holy shit supertrait implemented via subtrait

* implement most of the chain functions

* change to slightly better name

* implement fork

* fix outpoint handling in Chain struct

* update expect for work

* resolve review comment

* split utxo into two sets

* update the Chain definition

* just a little more

* update comment

* Apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

* apply changes from code review

* remove allow attribute in zebra-state/lib.rs

* Update zebra-state/src/memory_state.rs

Co-authored-by: teor <teor@riseup.net>

* merge ChainSet type into MemoryState

* rename state impl types

* Add error messages to asserts

* checkpoint so I can split off arbitrary changes into a PR

* export proptest impls for use in downstream crates

* add testjob for disabled feature in zebra-chain

* run rustfmt

* try to fix github actions syntax

* differentiate name

* prove that github action tests zebra-chain build without features

* revert change from last commit now that test is running

* remove accidentally introduced newline

* checkpoint

* add module doc comment

* update RFC for utxos

* add missing header

* working proptest for Chain

* apply change from chain impl PR

* setup config for proptests

* Update zebra-chain/src/block/arbitrary.rs

Co-authored-by: teor <teor@riseup.net>

* run rustfmt

Co-authored-by: teor <teor@riseup.net>
2020-10-02 15:51:51 -07:00
Jane Lusby 352721bd88
Implement RFC5: State updates `Chain` type (#1069)
* Begin work on RFC5 implementation

* I think this is necessary

* holy shit supertrait implemented via subtrait

* implement most of the chain functions

* change to slightly better name

* implement fork

* fix outpoint handling in Chain struct

* update expect for work

* resolve review comment

* split utxo into two sets

* update the Chain definition

* just a little more

* update comment

* Apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

* apply changes from code review

* remove allow attribute in zebra-state/lib.rs

* Update zebra-state/src/memory_state.rs

Co-authored-by: teor <teor@riseup.net>

* merge ChainSet type into MemoryState

* rename state impl types

* Add error messages to asserts

* add module doc comment

* update RFC for utxos

* add missing header

Co-authored-by: teor <teor@riseup.net>
2020-09-24 15:46:04 -07:00
Jane Lusby 0b4e974c9e
export proptest impls for use in downstream crates (#1092)
* export proptest impls for use in downstream crates

* add testjob for disabled feature in zebra-chain

* run rustfmt

* try to fix github actions syntax

* differentiate name

* prove that github action tests zebra-chain build without features

* revert change from last commit now that test is running

* remove accidentally introduced newline

* Update .github/workflows/ci.yml

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>
2020-09-23 18:52:52 -07:00
Deirdre Connolly 25f63518f4 Allow clippy::unit_arg because of derive(Arbitrary) 2020-08-17 11:46:34 -07:00
Henry de Valence 61dea90e2f chain: rename BlockHeaderHash to block::Hash
This is the first in a sequence of changes that change the block:: items
to not include Block as a prefix in their name, in accordance with the
Rust API guidelines.
2020-08-17 11:46:34 -07:00
Henry de Valence 855b89dec4 chain: create a new work module for proof-of-work
This extracts the `difficulty` module from `block` and the
`equihash_solution` module from the crate root.  The PoW calculations
are significantly more complicated than the other block code and pretty
dissimilar from it, so it makes more sense to create a common proof of
work module.

The `EquihashSolution` and `EQUIHASH_SOLUTION_SIZE` are renamed to
`equihash::Solution` and `equihash::SOLUTION_SIZE` and imported that
way, except in `block/header.rs`, to avoid a conflict with the
`equihash` crate.  In the future it would be better to encapsulate the
equihash solution check into the `equihash::Solution` type so that
callers only need to import our `work::equihash`.

The test organization leaves a little to be desired but I think that
this can be improved as we fill out the proof of work implementation.
2020-08-17 11:46:34 -07:00