1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use crate::{error::ConsensusError, Consensus};
use snarkvm_algorithms::CRH;
use snarkvm_dpc::{
base_dpc::{instantiated::*, record::DPCRecord},
AccountAddress,
DPCScheme,
Record,
};
use snarkvm_objects::{dpc::DPCTransactions, Block, BlockHeader, Storage, Transaction};
use snarkvm_posw::{txids_to_roots, PoswMarlin};
use snarkvm_utilities::{bytes::ToBytes, to_bytes};
use chrono::Utc;
use rand::{thread_rng, Rng};
use std::sync::Arc;
pub struct Miner<S: Storage> {
address: AccountAddress<Components>,
pub consensus: Arc<Consensus<S>>,
miner: PoswMarlin,
}
impl<S: Storage> Miner<S> {
pub fn new(address: AccountAddress<Components>, consensus: Arc<Consensus<S>>) -> Self {
Self {
address,
consensus,
miner: PoswMarlin::load().expect("could not instantiate the miner"),
}
}
pub fn fetch_memory_pool_transactions(&self) -> Result<DPCTransactions<Tx>, ConsensusError> {
let max_block_size = self.consensus.parameters.max_block_size;
let memory_pool = self.consensus.memory_pool.lock();
memory_pool.get_candidates(&self.consensus.ledger, max_block_size)
}
pub fn add_coinbase_transaction<R: Rng>(
&self,
transactions: &mut DPCTransactions<Tx>,
rng: &mut R,
) -> Result<Vec<DPCRecord<Components>>, ConsensusError> {
let program_vk_hash = to_bytes![ProgramVerificationKeyCRH::hash(
&self
.consensus
.public_parameters
.system_parameters
.program_verification_key_crh,
&to_bytes![
self.consensus
.public_parameters
.noop_program_snark_parameters
.verification_key
]?
)?]?;
let new_birth_programs = vec![program_vk_hash.clone(); NUM_OUTPUT_RECORDS];
let new_death_programs = vec![program_vk_hash.clone(); NUM_OUTPUT_RECORDS];
for transaction in transactions.iter() {
if self.consensus.parameters.network_id != transaction.network {
return Err(ConsensusError::ConflictingNetworkId(
self.consensus.parameters.network_id.id(),
transaction.network.id(),
));
}
}
let (records, tx) = self.consensus.create_coinbase_transaction(
self.consensus.ledger.get_current_block_height() + 1,
transactions,
program_vk_hash,
new_birth_programs,
new_death_programs,
self.address.clone(),
rng,
)?;
transactions.push(tx);
Ok(records)
}
#[allow(clippy::type_complexity)]
pub fn establish_block(
&self,
transactions: &DPCTransactions<Tx>,
) -> Result<(BlockHeader, DPCTransactions<Tx>, Vec<DPCRecord<Components>>), ConsensusError> {
let rng = &mut thread_rng();
let mut transactions = transactions.clone();
let coinbase_records = self.add_coinbase_transaction(&mut transactions, rng)?;
assert!(InstantiatedDPC::verify_transactions(
&self.consensus.public_parameters,
&transactions.0,
&*self.consensus.ledger,
)?);
let previous_block_header = self.consensus.ledger.get_latest_block()?.header;
Ok((previous_block_header, transactions, coinbase_records))
}
pub fn find_block<T: Transaction>(
&self,
transactions: &DPCTransactions<T>,
parent_header: &BlockHeader,
) -> Result<BlockHeader, ConsensusError> {
let txids = transactions.to_transaction_ids()?;
let (merkle_root_hash, pedersen_merkle_root_hash, subroots) = txids_to_roots(&txids);
let time = Utc::now().timestamp();
let difficulty_target = self.consensus.parameters.get_block_difficulty(parent_header, time);
let (nonce, proof) = self.miner.mine(
&subroots,
difficulty_target,
&mut thread_rng(),
self.consensus.parameters.max_nonce,
)?;
Ok(BlockHeader {
previous_block_hash: parent_header.get_hash(),
merkle_root_hash,
pedersen_merkle_root_hash,
time,
difficulty_target,
nonce,
proof: proof.into(),
})
}
pub fn mine_block(&self) -> Result<(Block<Tx>, Vec<DPCRecord<Components>>), ConsensusError> {
let candidate_transactions = self.fetch_memory_pool_transactions()?;
debug!("The miner is creating a block");
let (previous_block_header, transactions, coinbase_records) = self.establish_block(&candidate_transactions)?;
debug!("The miner generated a coinbase transaction");
for (index, record) in coinbase_records.iter().enumerate() {
let record_commitment = hex::encode(&to_bytes![record.commitment()]?);
debug!("Coinbase record {:?} commitment: {:?}", index, record_commitment);
}
let header = self.find_block(&transactions, &previous_block_header)?;
debug!("The Miner found a block");
let block = Block { header, transactions };
self.consensus.receive_block(&block)?;
let mut records_to_store = vec![];
for record in &coinbase_records {
if !record.is_dummy() {
records_to_store.push(record.clone());
}
}
self.consensus.ledger.store_records(&records_to_store)?;
Ok((block, coinbase_records))
}
}