Skip to content

Commit c972e40

Browse files
TinyChain --> docs added. / jsDoc fixed. / hasGenesisBlock script fixed.
1 parent b5f0c9f commit c972e40

8 files changed

Lines changed: 1136 additions & 15 deletions

File tree

docs/TinyChain/Block.md

Lines changed: 299 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,299 @@
1+
# 📦 `Block` – The Core Unit of TinyChain
2+
3+
A `Block` in TinyChain represents a single unit of immutable data added to the chain. Each block contains transaction data, cryptographic signatures, a timestamp, a reference to the previous block, and gas-related configuration.
4+
5+
Blocks are fundamental to the structure and security of the blockchain. They ensure data consistency, integrity, and trust through signature validation, hash linking, and mining mechanisms.
6+
7+
---
8+
9+
## 🧱 Constructor: `new Block(options)`
10+
11+
Creates a new instance of a blockchain block with all the required metadata, transaction records, and gas settings.
12+
13+
```js
14+
new Block({
15+
time,
16+
index,
17+
data,
18+
txs,
19+
sigs,
20+
chainId,
21+
prevHash,
22+
diff,
23+
baseFeePerGas,
24+
reward,
25+
nonce,
26+
miner,
27+
payloadString,
28+
signer,
29+
parser,
30+
hash,
31+
firstValidation,
32+
})
33+
```
34+
35+
### 🧾 Parameters
36+
37+
| Name | Type | Description |
38+
| ----------------- | ------------------------ | ------------------------------------------------------------------------------ |
39+
| `time` | `number` | Unix timestamp (in milliseconds) of block creation. |
40+
| `index` | `bigint \| string` | The block number in the chain. |
41+
| `data` | `TransactionData[]` | The list of transaction objects inside the block. |
42+
| `txs` | `Record<string, number>` | Optional transaction index mapping. |
43+
| `sigs` | `Record<string, string>` | Optional map of cryptographic signatures for each transaction. |
44+
| `chainId` | `bigint \| string` | The unique identifier of the blockchain instance. |
45+
| `prevHash` | `string` | Hash of the previous block (used for chaining). |
46+
| `diff` | `bigint \| string` | Difficulty level of the block (mining-related). |
47+
| `baseFeePerGas` | `bigint \| string` | Base gas price used to calculate transaction fees. |
48+
| `reward` | `bigint \| string` | The reward paid to the miner of the block. |
49+
| `nonce` | `bigint \| string` | The nonce used for mining the block. |
50+
| `miner` | `string \| null` | The address of the block's miner (if any). |
51+
| `payloadString` | `boolean` | Whether payloads should be kept as strings (default: `true`). |
52+
| `signer` | `TinySecp256k1` | ECDSA signer used for signature validation. |
53+
| `parser` | `TinyCryptoParser` | Parser used for serialization and hashing. |
54+
| `hash` | `string \| null` | Precomputed hash of the block. If not provided, it's calculated automatically. |
55+
| `firstValidation` | `boolean` | Whether to validate signatures on construction (default: `true`). |
56+
57+
### ❗ Errors Thrown
58+
59+
This constructor performs **strict type validation** and will throw descriptive errors if any required property is of the wrong type or if the data is invalid.
60+
61+
---
62+
63+
## 🧪 `validateSig()`
64+
65+
Validates all ECDSA signatures inside the block. Each transaction must be signed correctly by its sender.
66+
67+
```js
68+
block.validateSig();
69+
```
70+
71+
### 🔍 Behavior
72+
73+
* Loops through all transactions and signatures.
74+
* Serializes each transaction.
75+
* Uses the `TinySecp256k1` signer to validate against the address.
76+
* Throws an error if any signature is invalid or if an address is in the `invalidAddress` map.
77+
78+
---
79+
80+
## 🛑 `stopMining()`
81+
82+
Gracefully stops the mining process of a block.
83+
84+
```js
85+
block.stopMining();
86+
```
87+
88+
### 🔧 Usage
89+
90+
If you're running an asynchronous mining loop (e.g., in a Web Worker or async loop), calling `stopMining()` will set an internal flag that signals the miner to stop execution at the next opportunity.
91+
92+
This is helpful for cancellation or reconfiguration scenarios.
93+
94+
---
95+
96+
## 📤 `export()`
97+
98+
Serializes the current block instance to a string using the configured parser.
99+
100+
```js
101+
const exported = block.export();
102+
```
103+
104+
### 📦 Output
105+
106+
* Returns a deep stringified representation of all public block data.
107+
* Uses the `TinyCryptoParser.serializeDeep()` method internally.
108+
* Safe to store or transmit to other peers or clients.
109+
110+
---
111+
112+
## 📬 `get()`
113+
114+
Returns a plain object containing **only** the public data of the block.
115+
116+
```js
117+
const data = block.get();
118+
```
119+
120+
### 🔍 Output Shape
121+
122+
```js
123+
{
124+
chainId: bigint,
125+
index: bigint,
126+
time: number,
127+
data: TransactionData[],
128+
baseFeePerGas: bigint,
129+
prevHash: string,
130+
diff: bigint,
131+
nonce: bigint,
132+
hash: string,
133+
reward: bigint,
134+
miner: string | null,
135+
txs: Record<string, number>,
136+
sigs: Record<string, string>,
137+
}
138+
```
139+
140+
This is especially useful when you want to work with or inspect the contents of the block without exposing private methods or internals.
141+
142+
---
143+
144+
## 🧮 `calculateHash()`
145+
146+
Computes the hash of the block based on its current contents.
147+
148+
```js
149+
const hash = block.calculateHash();
150+
```
151+
152+
### 🔐 Behavior
153+
154+
* Combines the timestamp, previous hash, serialized data, signature list, index, gas data, nonce, and chain ID.
155+
* Uses SHA-256 to compute a deterministic hash.
156+
* The result is stored or compared as the block's ID.
157+
158+
### 🧊 Example
159+
160+
```js
161+
block.calculateHash(); // "e59cc8...7a32"
162+
```
163+
164+
The output is a `hex` string of the resulting SHA-256 digest.
165+
166+
---
167+
168+
## 🧾 `generateTxId(index)`
169+
170+
Generates a unique SHA-256 transaction ID for the item at the given index in the block's data.
171+
172+
```js
173+
const txId = block.generateTxId(0);
174+
```
175+
176+
### 🔒 Requirements
177+
178+
* The data must be an array.
179+
* The index must be within bounds.
180+
181+
### ❗ Throws
182+
183+
* `Error` if the index is not a valid number.
184+
* `Error` if the data is not an array or the index is invalid.
185+
186+
---
187+
188+
## ⛏️ `mine(minerAddress?, options?)`
189+
190+
Performs the mining loop asynchronously until a valid hash is found.
191+
192+
```js
193+
await block.mine("0xMinerAddress", {
194+
prevHash: "abcd1234",
195+
index: 2n,
196+
onProgress: (hashrate) => console.log(hashrate),
197+
onComplete: (finalHashrate) => alert(finalHashrate),
198+
});
199+
```
200+
201+
### 🛠️ Options
202+
203+
* `prevHash`: string (default: `"0"`)
204+
* `index`: bigint (default: `0n`)
205+
* `onProgress`: function (optional, receives hashrate updates)
206+
* `onComplete`: function (optional, called when mining succeeds)
207+
208+
### 🎯 Output
209+
210+
```js
211+
{
212+
nonce: bigint,
213+
hash: string,
214+
success: boolean
215+
}
216+
```
217+
218+
### ❗ Throws
219+
220+
* `Error` if the miner address is not a valid non-empty string.
221+
222+
---
223+
224+
## 📑 `getTxs()`
225+
226+
Returns the internal transaction ID map of the block.
227+
228+
```js
229+
const txs = block.getTxs();
230+
```
231+
232+
### 🔍 Output
233+
234+
A plain object mapping transaction IDs to their index in `data`.
235+
236+
### ❗ Throws
237+
238+
* `Error` if the internal map is not valid.
239+
240+
---
241+
242+
## 🔎 `getTx(txId)`
243+
244+
Fetches a transaction from `data` by its hashed transaction ID.
245+
246+
```js
247+
const tx = block.getTx("aabbccdd...");
248+
```
249+
250+
### ❗ Throws
251+
252+
* `Error` if the transaction ID does not exist.
253+
254+
---
255+
256+
## 🔐 `getParser()`
257+
258+
Returns the parser instance responsible for serialization.
259+
260+
```js
261+
const parser = block.getParser();
262+
```
263+
264+
### ❗ Throws
265+
266+
* `Error` if the parser is not a valid instance.
267+
268+
---
269+
270+
## ✍️ `getSigner()`
271+
272+
Returns the signer instance for signing and verifying.
273+
274+
```js
275+
const signer = block.getSigner();
276+
```
277+
278+
---
279+
280+
## 📊 Block Metadata Accessors
281+
282+
Simple getters that return validated internal values:
283+
284+
```js
285+
block.getTime(); // ⏱️ number
286+
block.getIndex(); // 🔢 bigint
287+
block.getChainId(); // 🆔 bigint
288+
block.getPrevHash(); // 🔗 string|null
289+
block.getDiff(); // 💪 bigint
290+
block.getReward(); // 💰 bigint
291+
block.getNonce(); // 🎲 bigint
292+
block.getMiner(); // 🧑‍🚀 string|null
293+
block.getData(); // 📦 TransactionData[]
294+
block.getSigs(); // ✍️ SignIndexMap
295+
block.getHash(); // 🧬 string
296+
block.getBaseFeePerGas();// ⛽ bigint
297+
```
298+
299+
All of them include internal validation to ensure type safety and correctness.

0 commit comments

Comments
 (0)