cruzbit 1.2.0

A simple decentralized peer-to-peer ledger implementation
Documentation
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use faster_hex::hex_encode;
use sha3::digest::generic_array::typenum::U32;
use sha3::digest::generic_array::GenericArray;
use sha3::{Digest, Sha3_256};

use crate::block::BlockHeader;
#[cfg(any(feature = "cuda", feature = "opencl"))]
use crate::gpu::{gpu_miner_mine, gpu_miner_update};
use crate::transaction::TransactionID;

#[derive(Clone, Default, Debug)]
pub struct BlockHeaderHasher {
    // these can change per attempt
    pub previous_hash_list_root: TransactionID,
    pub previous_time: u64,
    pub previous_nonce: u64,
    pub previous_transaction_count: u32,

    // used for tracking offsets of mutable fields in the buffer
    pub hash_list_root_offset: usize,
    pub time_offset: usize,
    pub nonce_offset: usize,
    pub transaction_count_offset: usize,

    // used for calculating a running offset
    pub time_len: usize,
    pub nonce_len: usize,
    pub tx_count_len: usize,

    // used for hashing
    pub initialized: bool,
    pub buf_len: usize,
    pub buffer: Vec<u8>,
    pub hasher: Sha3_256,
    /// SHA3-256 result bytes.
    pub result: GenericArray<u8, U32>,
    pub hashes_per_attempt: u64,
}

/// Static fields
pub const HDR_PREVIOUS: &[u8] = br#"{"previous":""#;
pub const HDR_HASH_LIST_ROOT: &[u8] = br#"","hash_list_root":""#;
pub const HDR_TIME: &[u8] = br#"","time":"#;
pub const HDR_TARGET: &[u8] = br#","target":""#;
pub const HDR_CHAIN_WORK: &[u8] = br#"","chain_work":""#;
pub const HDR_NONCE: &[u8] = br#"","nonce":"#;
pub const HDR_HEIGHT: &[u8] = br#","height":"#;
pub const HDR_TRANSACTION_COUNT: &[u8] = br#","transaction_count":"#;
pub const HDR_END: &[u8] = br#"}"#;

// calculate the maximum buffer length needed
const BUF_LEN: usize = HDR_PREVIOUS.len()
    + 64 // previous
    + HDR_HASH_LIST_ROOT.len()
    + 64 // hash_list_root
    + HDR_TIME.len()
    + 19 // time
    + HDR_TARGET.len()
    + 64 // target
    + HDR_CHAIN_WORK.len()
    + 64 // chain work
    + HDR_NONCE.len()
    + 19 // nonce
    + HDR_HEIGHT.len()
    + 19 // height
    + HDR_TRANSACTION_COUNT.len()
    + 10 // transaction_count
    + HDR_END.len();

impl BlockHeaderHasher {
    /// Returns a newly initialized BlockHeaderHasher
    pub fn new() -> Self {
        // initialize the hasher
        Self {
            buffer: vec![0; BUF_LEN],
            hashes_per_attempt: 1,
            ..Default::default()
        }
    }

    /// Initialize the buffer to be hashed
    pub fn init_buffer(&mut self, header: &mut BlockHeader) {
        // lots of slice copying to array offsets.

        // previous
        self.buffer[..HDR_PREVIOUS.len()].copy_from_slice(HDR_PREVIOUS);
        let mut buf_len = HDR_PREVIOUS.len();
        let _ = hex_encode(
            &header.previous,
            &mut self.buffer[buf_len..][..header.previous.len() * 2],
        );
        buf_len += header.previous.len() * 2;

        // hash_list_root
        self.previous_hash_list_root = header.hash_list_root;
        self.buffer[buf_len..][..HDR_HASH_LIST_ROOT.len()].copy_from_slice(HDR_HASH_LIST_ROOT);
        buf_len += HDR_HASH_LIST_ROOT.len();
        self.hash_list_root_offset = buf_len;
        let _ = hex_encode(
            &header.hash_list_root,
            &mut self.buffer[buf_len..][..header.hash_list_root.len() * 2],
        );
        buf_len += header.hash_list_root.len() * 2;

        // time
        self.previous_time = header.time;
        self.buffer[buf_len..][..HDR_TIME.len()].copy_from_slice(HDR_TIME);
        buf_len += HDR_TIME.len();
        self.time_offset = buf_len;
        let mut int_buf = itoa::Buffer::new();
        let time_str = int_buf.format(header.time);
        self.buffer[buf_len..buf_len + time_str.len()].copy_from_slice(time_str.as_bytes());
        self.time_len = time_str.len();
        buf_len += time_str.len();

        // target
        self.buffer[buf_len..][..HDR_TARGET.len()].copy_from_slice(HDR_TARGET);
        buf_len += HDR_TARGET.len();
        let _ = hex_encode(
            &header.target,
            &mut self.buffer[buf_len..][..header.target.len() * 2],
        );
        buf_len += header.target.len() * 2;

        // chain_work
        self.buffer[buf_len..][..HDR_CHAIN_WORK.len()].copy_from_slice(HDR_CHAIN_WORK);
        buf_len += HDR_CHAIN_WORK.len();

        let _ = hex_encode(
            &header.chain_work,
            &mut self.buffer[buf_len..buf_len + header.chain_work.len() * 2],
        );
        buf_len += header.chain_work.len() * 2;

        // nonce
        self.previous_nonce = header.nonce;
        self.buffer[buf_len..][..HDR_NONCE.len()].copy_from_slice(HDR_NONCE);
        buf_len += HDR_NONCE.len();
        self.nonce_offset = buf_len;
        let nonce_str = int_buf.format(header.nonce);
        self.buffer[buf_len..][..nonce_str.len()].copy_from_slice(nonce_str.as_bytes());
        self.nonce_len = nonce_str.len();
        buf_len += nonce_str.len();

        // height
        self.buffer[buf_len..][..HDR_HEIGHT.len()].copy_from_slice(HDR_HEIGHT);
        buf_len += HDR_HEIGHT.len();
        let height_str = int_buf.format(header.height);
        self.buffer[buf_len..][..height_str.len()].copy_from_slice(height_str.as_bytes());
        buf_len += height_str.len();

        // transaction_count
        self.previous_transaction_count = header.transaction_count;
        self.buffer[buf_len..][..HDR_TRANSACTION_COUNT.len()]
            .copy_from_slice(HDR_TRANSACTION_COUNT);
        buf_len += HDR_TRANSACTION_COUNT.len();
        self.transaction_count_offset = buf_len;
        let transaction_count_str = int_buf.format(header.transaction_count);
        self.buffer[buf_len..][..transaction_count_str.len()]
            .copy_from_slice(transaction_count_str.as_bytes());
        self.tx_count_len = transaction_count_str.len();
        buf_len += transaction_count_str.len();

        // end
        self.buffer[buf_len..][..HDR_END.len()].copy_from_slice(HDR_END);
        buf_len += HDR_END.len();
        self.buf_len = buf_len;

        self.initialized = true;
    }

    /// Is called every time the header is updated and the caller wants its new hash value/ID.
    pub fn update(_miner_num: usize, header: &mut BlockHeader, hasher: &mut BlockHeaderHasher) {
        let device_mining = cfg!(feature = "cuda") || cfg!(feature = "opencl");
        let mut _buffer_changed = false;

        if !hasher.initialized {
            hasher.init_buffer(header);
            _buffer_changed = true;
        } else {
            // hash_list_root
            if hasher.previous_hash_list_root != header.hash_list_root {
                _buffer_changed = true;
                // write out the new value
                hasher.previous_hash_list_root = header.hash_list_root;
                let _ = hex_encode(
                    &header.hash_list_root,
                    &mut hasher.buffer[hasher.hash_list_root_offset..]
                        [..header.hash_list_root.len() * 2],
                );
            }

            let mut offset = 0;
            let mut int_buf = itoa::Buffer::new();

            // time
            if hasher.previous_time != header.time {
                _buffer_changed = true;
                hasher.previous_time = header.time;

                // write out the new value
                let mut buf_len = hasher.time_offset;
                let time_str = int_buf.format(header.time);
                let time_len = time_str.len();
                hasher.buffer[buf_len..buf_len + time_len].copy_from_slice(time_str.as_bytes());
                buf_len += time_len;

                // did time shrink or grow in length?
                offset = time_len as isize - hasher.time_len as isize;
                hasher.time_len = time_len;

                if offset != 0 {
                    // shift everything below up or down

                    // target
                    hasher.buffer[buf_len..buf_len + HDR_TARGET.len()].copy_from_slice(HDR_TARGET);
                    buf_len += HDR_TARGET.len();
                    let _ = hex_encode(
                        &header.target,
                        &mut hasher.buffer[buf_len..buf_len + header.target.len() * 2],
                    );
                    buf_len += header.target.len() * 2;

                    // chain_work
                    hasher.buffer[buf_len..buf_len + HDR_CHAIN_WORK.len()]
                        .copy_from_slice(HDR_CHAIN_WORK);
                    buf_len += HDR_CHAIN_WORK.len();
                    let _ = hex_encode(
                        &header.chain_work,
                        &mut hasher.buffer[buf_len..buf_len + header.chain_work.len() * 2],
                    );
                    buf_len += header.chain_work.len() * 2; // hex bytes written

                    // start of nonce
                    hasher.buffer[buf_len..buf_len + HDR_NONCE.len()].copy_from_slice(HDR_NONCE);
                }
            }

            // nonce
            if offset != 0 || (!device_mining && hasher.previous_nonce != header.nonce) {
                _buffer_changed = true;
                hasher.previous_nonce = header.nonce;

                // write out the new value (or old value at a new location)
                hasher.nonce_offset = (hasher.nonce_offset as isize + offset) as usize;
                let mut buf_len = hasher.nonce_offset;
                let nonce_str = int_buf.format(header.nonce);
                let nonce_len = nonce_str.len();
                hasher.buffer[buf_len..buf_len + nonce_len].copy_from_slice(nonce_str.as_bytes());
                buf_len += nonce_len;

                // did nonce shrink or grow in length?
                offset += nonce_len as isize - hasher.nonce_len as isize;
                hasher.nonce_len = nonce_len;

                if offset != 0 {
                    // shift everything below up or down

                    // height
                    hasher.buffer[buf_len..buf_len + HDR_HEIGHT.len()].copy_from_slice(HDR_HEIGHT);
                    buf_len += HDR_HEIGHT.len();
                    let height_str = int_buf.format(header.height);
                    let height_len = height_str.len();
                    hasher.buffer[buf_len..buf_len + height_len]
                        .copy_from_slice(height_str.as_bytes());
                    buf_len += height_len;

                    // start of transaction_count
                    hasher.buffer[buf_len..buf_len + HDR_TRANSACTION_COUNT.len()]
                        .copy_from_slice(HDR_TRANSACTION_COUNT);
                }
            }

            // transaction_count
            if offset != 0 || hasher.previous_transaction_count != header.transaction_count {
                _buffer_changed = true;
                hasher.previous_transaction_count = header.transaction_count;

                // write out the new value (or old value at a new location)
                hasher.transaction_count_offset =
                    (hasher.transaction_count_offset as isize + offset) as usize;
                let mut buf_len = hasher.transaction_count_offset;
                let transaction_count_str = int_buf.format(header.transaction_count);
                let tx_count_len = transaction_count_str.len();
                hasher.buffer[buf_len..buf_len + tx_count_len]
                    .copy_from_slice(transaction_count_str.as_bytes());
                buf_len += tx_count_len;

                // did count shrink or grow in length?
                offset += tx_count_len as isize - hasher.tx_count_len as isize;
                hasher.tx_count_len = tx_count_len;

                if offset != 0 {
                    // shift the footer up or down
                    hasher.buffer[buf_len..buf_len + HDR_END.len()].copy_from_slice(HDR_END);
                }
            }

            // it's possible (likely) we did a bunch of encoding with no net impact to the buffer length
            hasher.buf_len = (hasher.buf_len as isize + offset) as usize;
        }

        #[cfg(any(feature = "cuda", feature = "opencl"))]
        {
            // devices don't return a hash just a solving nonce (if found)
            let nonce = hasher.update_device(_miner_num, header, _buffer_changed);
            if nonce == 0x7fffffff_ffffffff {
                // not found - keep all-0xFF so the host loop sees a value
                // greater than any valid target
                hasher.result.fill(0xff);
                return;
            } else {
                log::info!(
                    "GPU miner {_miner_num} found a possible solution: {nonce}, double-checking it..."
                );
                // rebuild the buffer with the new nonce since we don't update it
                // per attempt when using CUDA/OpenCL.
                header.nonce = nonce;
                hasher.init_buffer(header);
            }
        }

        // hash it
        hasher.hasher.update(&hasher.buffer[..hasher.buf_len]);
        hasher.hasher.finalize_into_reset(&mut hasher.result);
    }

    /// Handle mining with GPU devices
    #[cfg(any(feature = "cuda", feature = "opencl"))]
    pub fn update_device(
        &mut self,
        miner_num: usize,
        header: &BlockHeader,
        buffer_changed: bool,
    ) -> u64 {
        if buffer_changed {
            // update the device's copy of the buffer
            // the device formats the current nonce itself, so nonce-width
            // changes don't require refreshing this suffix.
            let last_offset = self.nonce_offset + self.nonce_len;
            self.hashes_per_attempt = gpu_miner_update(
                miner_num,
                &self.buffer,
                self.buf_len,
                self.nonce_offset,
                last_offset,
                &header.target,
            );
        }

        // try for a solution
        gpu_miner_mine(miner_num, header.nonce)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::block::test_utils::make_test_block;
    use crate::block::{Block, BlockID};

    #[test]
    fn test_block_header_hasher() {
        let mut block = make_test_block(10);
        assert!(compare_ids(&mut block), "ID mismatch 1");

        block.header.time = 1234;
        assert!(compare_ids(&mut block), "ID mismatch 2");

        block.header.nonce = 1234;
        assert!(compare_ids(&mut block), "ID mismatch 3");

        block.header.nonce = 1235;
        assert!(compare_ids(&mut block), "ID mismatch 4");

        block.header.nonce = 1236;
        block.header.time = 1234;
        assert!(compare_ids(&mut block), "ID mismatch 5");

        block.header.time = 123498;
        block.header.nonce = 12370910;
        let tx = &block.transactions[1];
        let tx_id = tx.id().unwrap();
        block.add_transaction(tx_id, tx.clone()).unwrap();
        assert!(compare_ids(&mut block), "ID mismatch 6");

        block.header.time = 987654321;
        assert!(compare_ids(&mut block), "ID mismatch 7");
    }

    #[test]
    fn test_block_header_hasher_reuses_buffer_across_length_changes() {
        let mut block = make_test_block(10);
        let mut hasher = BlockHeaderHasher::new();

        assert!(
            compare_ids_with_hasher(&mut block, &mut hasher),
            "ID mismatch 1"
        );

        block.header.time = 9;
        assert!(
            compare_ids_with_hasher(&mut block, &mut hasher),
            "ID mismatch 2"
        );

        block.header.time = 10;
        assert!(
            compare_ids_with_hasher(&mut block, &mut hasher),
            "ID mismatch 3"
        );

        block.header.nonce = 99;
        assert!(
            compare_ids_with_hasher(&mut block, &mut hasher),
            "ID mismatch 4"
        );

        block.header.nonce = 100;
        assert!(
            compare_ids_with_hasher(&mut block, &mut hasher),
            "ID mismatch 5"
        );

        block.header.transaction_count = 99;
        assert!(
            compare_ids_with_hasher(&mut block, &mut hasher),
            "ID mismatch 6"
        );

        block.header.transaction_count = 100;
        assert!(
            compare_ids_with_hasher(&mut block, &mut hasher),
            "ID mismatch 7"
        );
    }

    #[test]
    fn test_device_header_bytes_ignore_cached_nonce_width() {
        let mut block = make_test_block(10);
        block.header.nonce = 9;

        let mut hasher = BlockHeaderHasher::new();
        hasher.init_buffer(&mut block.header);

        assert_eq!(
            device_header_bytes(&block, &hasher),
            serde_json::to_vec(&block.header).unwrap()
        );

        block.header.nonce = 10;
        assert_eq!(
            device_header_bytes(&block, &hasher),
            serde_json::to_vec(&block.header).unwrap()
        );

        block.header.nonce = 100;
        assert_eq!(
            device_header_bytes(&block, &hasher),
            serde_json::to_vec(&block.header).unwrap()
        );
    }

    fn compare_ids(block: &mut Block) -> bool {
        // compute header ID
        let id = block.id().unwrap();

        // use delta method
        let mut hasher = BlockHeaderHasher::new();
        block.header.id_fast(0, &mut hasher);
        let id2 = BlockID::from(&hasher.result[..]);
        id == id2
    }

    fn compare_ids_with_hasher(block: &mut Block, hasher: &mut BlockHeaderHasher) -> bool {
        let id = block.id().unwrap();
        block.header.id_fast(0, hasher);
        let id2 = BlockID::from(&hasher.result[..]);
        id == id2
    }

    fn device_header_bytes(block: &Block, hasher: &BlockHeaderHasher) -> Vec<u8> {
        let mut nonce_buf = itoa::Buffer::new();
        let nonce_str = nonce_buf.format(block.header.nonce);
        let last_offset = hasher.nonce_offset + hasher.nonce_len;

        let mut bytes = Vec::with_capacity(
            hasher.nonce_offset + nonce_str.len() + hasher.buf_len - last_offset,
        );
        bytes.extend_from_slice(&hasher.buffer[..hasher.nonce_offset]);
        bytes.extend_from_slice(nonce_str.as_bytes());
        bytes.extend_from_slice(&hasher.buffer[last_offset..hasher.buf_len]);
        bytes
    }
}