Repository navigation
Releases
Releases · cpoli/blockchainkit
blockchainkit 0.3.0
Added
blockchainkit.contracts, a sixth subpackage on designing, breaking and
verifying smart contracts, with a history page of 17 breakthroughs, each
with its own gallery example, from Floyd and Hoare (1967-1969) to
Beanstalk's flash-loan governance attack (2022), and an exercise page.
New APIs: the world-state modelWorldandContract(call,
delegatecall,send, CREATE and CREATE2, events,selfdestruct, gas,
per-call rollback, invariants) withcreate_addressand
create2_address;weakest_precondition,check_tripleand
run_program;symbolic_execute,symbolic_bytecode(forvm
programs) andsolve;requiresandensures;fuzzandshrink;
Ricardian contracts;MintandPurse; ERC-20 and ERC-721 tokens; King
of the Ether, GovernMental, block-hash and commit-reveal lotteries; the
Parity wallet libraries; naive and EIP-1967 proxies; a CREATE2 factory;
and flash-loan governance. Plots:plot_call_tree,
plot_symbolic_pathsandplot_storage.blockchainkit.economics, a seventh subpackage on incentives, fees and
markets, with a history page of 16 breakthroughs, each with its own
gallery example, from Schelling's focal points (1960) to proposer-builder
separation (2022), and an exercise page. New APIs:coordination_probability
andschelling_round; first- and second-price auctions, virtual values,
equilibrium bids and expected revenue; the logarithmic market scoring
rule;block_subsidy,issued_supplyanddouble_spend_incentive;
simulate_block_rewards,mining_gapandundercutting_payoffs;
optimal_mining_revenueandhonest_mining_is_equilibrium;
next_base_feeandsimulate_fee_market;amount_out,
impermanent_lossand theConstantProductPoolcontract; Dai's
VaultEnginewithStablecoinandPriceFeed; theOracleLenderand
OracleAttackercontracts;priority_gas_auction,sandwich_profitand
sandwich_attack; andsimulate_pbs. Plots:plot_fee_market,
plot_constant_productandplot_gas_auction. The model boundaries page
gains an "Economic models" section.blockchainkit.channels, an eighth subpackage on layer-2 scaling and
interoperability, with a history page of 16 breakthroughs, each with its
own gallery example, from Reed-Solomon codes (1960) to the Ronin and
Wormhole bridge exploits (2022), and an exercise page. New APIs:
rs_encode,rs_recoverandrs_decode(Berlekamp-Welch);
SpilmanChannel,DuplexChannelwithinvalidation_locktimes,
LightningChannel(revocation keys, shachain secrets, penalties),
EltooChannel, and theStateChannelandPreimageManagercontracts,
all with Script outputs checked byvm.verify_script;Watchtower,
make_appointmentand PISA'stower_liable;ChannelNetworkfor
multi-hop HTLC routing andprobe_balance;AtomicSwap; theBTCRelay
contract andmine_header;ValidatorBridge,GuardianVerifierand
WormholeBridge;PlasmaChainwith Plasma Cash exits;
shard_failure_probabilityandatomix_transfer;ZKRollup,
OptimisticRollupandbisect; andextend,simulate_samplingand
encoding fraud proofs for data availability. Plots:plot_shares,
plot_routeandplot_detection. The model boundaries page gains a
"Channels, rollups and bridges" section.blockchainkit.proofs, a ninth subpackage on zero-knowledge and succinct
proof systems, with a history page of 16 breakthroughs, each with its own
gallery example, from the Schwartz-Zippel lemma (1980) to Halo (2019),
and an exercise page. New APIs: polynomial arithmetic, interpolation and
the FFT over the BabyBear field (FIELD_PRIME) and a Fiat-Shamir
Transcript;identity_test;sumcheckandmultilinear_extension;
tqbf_protocol;hadamard_proofandpcp_verify;kilian_argument,
micali_proofandverify_cs_proof; a toy supersingular
PAIRING_CURVEwith the Tatepairing; KZG (trusted_setup,
kzg_commit,kzg_open,kzg_verify,forge_opening); powers-of-tau
ceremonies (contribute,verify_contribution); the R1CS builder
Circuit,r1cs_to_qapandqap_divide; Groth16; MiMC and a Zerocash
ShieldedPoolwithprove_spend;PlonkCircuitand PLONK with
permutation_product; Bulletproofsrange_proof;fri_proveand
fri_verify; a Fibonaccistark_prove; and Halo'sipa_open,
ipa_defer,accumulateanddecide. Plots:plot_field_polynomials,
plot_proof_sizesandplot_copy_constraints. The model boundaries page
gains a "Proof systems" section, andblockchainkit.constantsthe
TRANSCRIPT_DOMAIN,IPA_GENERATOR_DOMAINandMIMC_DOMAINtags.blockchainkit.fraud, a tenth subpackage on financial fraud on and
around blockchains, with a history page of 17 breakthroughs, each with its
own gallery example, from Ponzi's scheme (1920) to address poisoning
(2022-2023), and an exercise page. New APIs:simulate_ponzi,
breakeven_growth,simulate_lending_ponziandreferral_commissions;
theChainPonzicontract withvalue_flowsandponzi_features;
benford_test; theMerkleSumTreewithverify_sum_proof,
liability_tree,auditandreserve_ratio; Provisions-style proofs of
solvency (SolvencyProver,verify_solvency, OR proofs and bitwise
range proofs over Pedersen commitments);reissue_missingand the
Custodiancontract;verify_sourceandeffective_code; the
TokenSale(DAICO) contract; seven Torres et al. honeypot contracts with
explorer_view;SellBlockToken,HiddenMintTokenandsell_test;
simulate_bot_market,return_by_activity,simulate_pump_and_dump
anddetect_pumps;find_wash_tradesandsimulate_nft_market; the
Drainercontract withopen_approvalsandallowance_exposure; and
grind_lookalikeandpoisoning_suspects. Plots:plot_ponzi,
plot_benfordandplot_price_spikes. The model boundaries page gains
a "Fraud models" section, andblockchainkit.constantsthe
SUM_LEAF_DOMAIN,SUM_NODE_DOMAIN,SOLVENCY_DOMAINand
LOOKALIKE_DOMAINtags.blockchainkit.privacy, an eleventh subpackage on anonymity and
confidentiality on public ledgers, with a history page of 15
breakthroughs, each with its own gallery example, from Chaum's mix-nets
(1981) to Tornado Cash (2019), and an exercise page. New APIs:MixNode,
seal,wrapandmix_cascade;circuit_compromise_rate,
simulate_flowsandmatch_flows;k_anonymity,equivalence_classes
andeffective_anonymity_set;ring_signandring_verify;
lsag_sign,mlsag_sign,key_imageandlinked;simulate_payments,
cluster_addressesandscore_clusters;stealth_keys,
stealth_payment,owns_outputandone_time_secret;coinjoinand
link_change; the RSA accumulator,ZerocoinPooland
prove_zerocoin_spend; ring-signature range proofs and
verify_confidential;ringct_spendandverify_ringct;
mimblewimble_transaction,aggregateandcut_through; the TumbleBit
Tumblerwithrun_tumbler;simulate_rings,chain_reactionand
trace_rings; and theMixercontract withprove_withdrawaland
mixer_report, proving with the Zerocash circuit ofproofs. Plots:
plot_cluster_sizes,plot_ring_positionsandplot_anonymity_sets.
The model boundaries page gains a "Privacy models" section, and
blockchainkit.constantstheMIX_DOMAIN,RING_DOMAIN,
KEY_IMAGE_DOMAIN,STEALTH_DOMAIN,KERNEL_DOMAIN,
ACCUMULATOR_DOMAINandTUMBLER_DOMAINtags.blockchainkit.wallets, a twelfth subpackage on keys as users actually
hold them, with a history page of 15 breakthroughs, each with its own
gallery example, from BCH codes (1959-1960) to ERC-4337 account
abstraction (2021), and an exercise page. New APIs:BCHCodeand
minimal_polynomial;verhoeff_digit,luhn_digitand
detection_rates;pbkdf2andcrack_pin;scrypt,salsa20_8,
block_mixandromixwith a memory-time trade-off; Base58Check,
p2pkh_addressandis_valid_address;bech32_encode,
bech32_decode,segwit_encode,segwit_decodeandp2wpkh_address
for Bech32 and Bech32m;serialize_script,multisig_redeem_script
andverify_p2sh; BIP32'smaster_key,derive_private,
derive_public,serialize_extended_keyandrecover_parent_private;
BIP39'sentropy_to_mnemonicandmnemonic_to_seed; BIP44's
derive_pathanddiscover_accounts;brain_wallet_keyand
simulate_brain_drain;ecdsa_signandecdsa_verify;
threshold_keygenandthreshold_sign; theSocialRecoveryWallet
contract withrecovery_risk; and ERC-4337'sEntryPoint,
SmartAccountandbundle. Utilities: RIPEMD-160 andhash160,
compressed secp256k1 keys, and GF(2**m). Plots:
plot_detection_rates,plot_memory_tradeoffandplot_recovery_risk.
The model boundaries page gains a "Wallet models" section, and
blockchainkit.constantstheHARDENED_OFFSET,BIP32_SEED_KEY,
BIP39_SALT_PREFIX,MAX_SCRIPT_ELEMENT_SIZEand
USER_OPERATION_DOMAINconstants.World.fork()inblockchainkit.contracts: an independent copy of the
world state on which to try transactions, as a wallet simulates one
before sending it.- Domain tags for contract addresses, block hashes, Ricardian contracts,
lottery commitments and wallet approvals inblockchainkit.constants,
and for channel states, Plasma transfers, rollup state, bridge
withdrawals and watchtower appointments,
and a "Contract world model" section in the model boundaries page.
Fixed
consensus.systems.fork_choiceimportsstructuresonly for type
checking, so a subpackage that loadsstructuresbeforeconsensusno
longer hits a circular import.FinalityGadgetno longer depends on vote arrival order: justification and
finality are recomputed over every recorded vote, so a supermajority link
recorded before ...
blockchainkit 0.2.0
The package is aligned with its kit-family siblings, and every subpackage now
follows its field through at least 15 breakthroughs, each with its own
experiment.
Added
- Tutorials across subpackages, every line run by the doctest build: Life of
a payment, Nonces everywhere, Hashes everywhere and Who do you
trust?. - Exercise pages, one per subpackage, with 40 worked solutions in collapsed
boxes, each run by the doctest build. They replace the single solutions page. - A "Teaching vs production" note on every history entry that adapts a
deployed protocol, naming the difference. - README figures, regenerated by
docs/make_readme_figure.pyand
docs/make_readme_subpackage_figures.py. - Execution history: 16 breakthroughs, each with its own gallery example,
from reverse Polish notation (1924-1957) to the BeautyChain overflow
(2018). New APIs:execute(..., arguments=...), the Forth wordsOVERand
ROT,REVERT, and the sharedSTACK_EFFECTStable;validate_program;
assemble(labels);to_rpnandcompile_expression;verify_bytecode
andVerificationResult;run_turing_machine,enumerate_machinesand
busy_beaver(reproducing S(2) = 6); Bitcoin-style Script with
verify_script,p2pkh_locking/p2pkh_unlockingandhtlc_locking
(OP_CHECKLOCKTIMEVERIFY); the contractsvending_machineand
batch_transfer(BEC overflow, with a SafeMath option);drain_bank
(DAO reentrancy); and the plotplot_stack_height. - Network history: 17 breakthroughs, each with its own gallery example, from
Erdős-Rényi random graphs (1959) to Dandelion (2017). New APIs:Graph,
erdos_renyi,ring_lattice,watts_strogatz,barabasi_albertand
complete_graph;lamport_timestamps,vector_timestamps,
happened_beforeandconcurrent;spread_rumor(push, pull, push-pull)
andpittel_rounds;reliable_broadcast(Bracha);ReplicatedRegister
(CAP);KademliaNetwork,xor_distanceandnode_id;AddressManager
andeclipse_probability;relay_cost,compact_block_relayand
short_id;fork_rateandsimulate_fork_rate;first_spy_precision;
SimulatedNetwork.from_graphandSimulatedNetwork.messages_sent; the
plotsplot_graph,plot_space_timeandplot_rumor_spread; and the
COMPACT_BLOCK_DOMAINconstant. - Consensus history: 17 breakthroughs, each with its own gallery example,
from the gambler's ruin (1656) to Casper FFG (2017). New APIs:
oral_messages(Byzantine generals);ben_or(randomized consensus, also
used to show the FLP adversary);view_changes(partial synchrony);
modular_square_root(Dwork-Naor pricing);pbft_roundand
quorum_size;attacker_success_probability(whitepaper section 11, checked
against its table);retargetandsimulate_difficulty;ghost_tipand
subtree_work;selfish_mining_revenue,selfish_mining_thresholdand
simulate_selfish_mining;fork_voting_payoffs(nothing at stake);
sortition; andFinalityGadget(Casper FFG with slashing detection). - Structures history: 15 breakthroughs, each with its own gallery example,
from double-entry bookkeeping (1494) to Merkle mountain ranges (2016). New
APIs:Ledger.total_supply;BloomFilter;hash_chainand
verify_one_time_password;BlockHeader,Block.to_header()and
verify_header_chainfor light clients;bitcoin_merkle_root(Bitcoin's
duplicated-leaf convention, for CVE-2012-2459);MerkleTree.consistency_proof
andverify_consistency(RFC 6962/9162);UTXOSet,UTXOTransaction,
OutPointandCoin;Transaction.unsigned_id(SegWit-style);
SparseMerkleTreewith membership and non-membership proofs; and
MerkleMountainRange. - Cryptography history: 22 breakthroughs, each with its own gallery example,
from the one-time pad (1917-1949) to MuSig (2018). New APIs behind them:
one_time_pad/xor_bytes;baby_step_giant_stepandpohlig_hellman;
merkle_puzzles/solve_puzzle;lamport_keypair/lamport_sign/
lamport_verify;find_collision/truncated_hash; a readable
Merkle-Damgard SHA-256 (merkle_damgard_sha256,sha256_compress,
sha256_padding) withlength_extension;naive_macandhmac_sha256;
pedersen_commit/pedersen_generators;feldman_split/feldman_verify;
TEACHING_GROUP, a 62-bit safe-prime group;simulate_transcript;
deterministic_nonce(RFC 6979, checked against the RFC's vectors); and
musig_coefficients/aggregate_public_keys/musig_sign. visualizers/in every subpackage (Matplotlib, imported explicitly; plain
import blockchainkitstill loads only the standard library):
plot_curve_points,plot_hamming_distances,plot_merkle_tree,
plot_proof_trace,plot_block_tree,plot_mining_trials,
plot_stake_shares,plot_gossip_timeline,plot_execution_trace.
Matplotlib and NumPy are now runtime dependencies; theexamplesextra is
gone.execute(..., trace=True)records aTraceStepafter every instruction,
following jumps; a failed run carries its partial trace inVMError.trace.
execute(..., gas_costs=...)prices opcodes individually (each at least 1).MerkleTree.levels,MerkleTree.leaf_count, andtrace_proof, which
returns aMerkleTraceofProofSteps, even for a proof that fails.Blockchain.blocks,tips(),work_at()andstate_at()to inspect
side forks.enumerate_pointslists every point of a small curve.
Changed
- The documentation follows the kit-family structure: generated hub pages per
subpackage, per-subpackage API pages, ahistory/directory with one
breakthroughs page per subpackage (each entry with its own References:
line andminigallery), an examples index, tutorials (the guided course and
solutions), and JupyterLite launch buttons. Examples moved to
examples/<subpackage>/<topic>/. The committed per-example notebooks and
their sync scripts are replaced by sphinx-gallery downloads and a single
notebooks/quickstart.ipynb. - The package uses the kit-family layout: one subpackage per domain with
core/,systems/,utils/andtests/, shared validation in
_validation.py, and every consensus-relevant constant inconstants.py.
Publicbk.<subpackage>.<name>imports are unchanged. - A wrong argument type (bool, float, string) now raises
TypeError; an
out-of-range integer still raisesValueError.multiplyreports the two
cases separately. - Mining varies only the header nonce:
Block.merkle_rootandBlock.hash
are cached, andBlock.header(nonce=...)builds a candidate header without
rebuilding the Merkle tree. Mining a 20-transaction block is about 59 times
faster per attempt (2 µs instead of 118 µs). verifyskips the subgroup-membership multiplications when Hasse's bound
proves the cofactor is 1 (newCurve.cofactor_is_one), halving the cost of
verification on secp256k1.Ledger,Blockchain,MerkleTreeandSimulatedNetworkhave readable
reprs.
Fixed
Transactionrejects asignaturethat is not aSchnorrSignature;
before, the block hash raisedAttributeErrorlater.executeraisesVMError, notTypeError, for a non-string opcode.Curveaccepts secp256k1's field prime and group order only in their own
roles; swapping them no longer skips the primality check.- A receive callback that raises no longer leaves the payload marked seen.
eventual_catch_uprejects non-numeric fractions, andStakeSamplerand
SimulatedNetworkreject non-integer seeds.