Embedded SDK
Embedded SDK
Loading...
Searching...
No Matches
fuzz_bip32.h
Go to the documentation of this file.
1#pragma once
12#include <stddef.h>
13#include <stdint.h>
14
15#include "os_utils.h" // U4BE_ENCODE
16
17typedef struct {
18 const uint32_t *purposes; /* e.g. {44, 49, 84, 86} */
19 size_t n_purposes;
20 uint32_t coin_type; /* e.g. 0x80000000 | 1 for testnet */
21 uint8_t max_account; /* max account index (0-based) */
22 uint8_t max_depth; /* max total path depth (3-5 typical) */
24
25// Build a BIP32 path into buf from ctrl bytes: [0] purpose, [1] account,
26// [2] depth selector, [3..] extra child indices. Returns bytes written or 0.
27static inline size_t fuzz_bip32_build(const fuzz_bip32_config_t *cfg,
28 const uint8_t *ctrl,
29 size_t ctrl_len,
30 uint8_t *buf,
31 size_t buf_size)
32{
33 if (!cfg || cfg->n_purposes == 0 || !cfg->purposes) {
34 return 0;
35 }
36
37 uint8_t min_depth = 3;
38 uint8_t max_depth = cfg->max_depth;
39 if (max_depth < min_depth) {
40 max_depth = min_depth;
41 }
42
43 uint8_t depth = min_depth;
44 if (ctrl_len > 2 && max_depth > min_depth) {
45 depth = min_depth + (ctrl[2] % (max_depth - min_depth + 1));
46 }
47
48 size_t needed = 1 + (size_t) depth * 4;
49 if (buf_size < needed) {
50 return 0;
51 }
52
53 uint32_t purpose = cfg->purposes[0];
54 if (ctrl_len > 0) {
55 purpose = cfg->purposes[ctrl[0] % cfg->n_purposes];
56 }
57
58 uint32_t account = 0;
59 if (ctrl_len > 1 && cfg->max_account > 0) {
60 account = ctrl[1] % ((uint32_t) cfg->max_account + 1);
61 }
62
63 uint8_t *p = buf;
64 *p++ = depth;
65
66 U4BE_ENCODE(p, 0, 0x80000000UL | purpose);
67 p += 4;
68
69 if (depth > 1) {
70 U4BE_ENCODE(p, 0, cfg->coin_type);
71 p += 4;
72 }
73
74 if (depth > 2) {
75 U4BE_ENCODE(p, 0, 0x80000000UL | account);
76 p += 4;
77 }
78
79 for (uint8_t i = 3; i < depth; i++) {
80 uint32_t child = 0;
81 size_t ctrl_idx = 3 + (size_t) (i - 3);
82 if (ctrl_idx < ctrl_len) {
83 child = ctrl[ctrl_idx] % 2;
84 }
85 U4BE_ENCODE(p, 0, child);
86 p += 4;
87 }
88
89 return (size_t) (p - buf);
90}
static size_t fuzz_bip32_build(const fuzz_bip32_config_t *cfg, const uint8_t *ctrl, size_t ctrl_len, uint8_t *buf, size_t buf_size)
Definition fuzz_bip32.h:27
const uint32_t * purposes
Definition fuzz_bip32.h:18