TBlockChain
Source: source/internal/TBlockChain.prg
Standalone class
TBlockChain is a pure Harbour blockchain implementation with SHA-256 hashing, proof-of-work mining, and block validation. It uses a CLASSDATA hash (aBlocks) so all instances share the same chain, enabling multi-window applications to operate on the same data. The chain stores an array of hashed blocks, each containing a timestamp, data payload, once (nonce), and the previous block's hash. Mining iterates through nonce values until the hash matches the difficulty prefix.
Key DATA Members
| DATA | Type | Description |
|---|---|---|
aBlocks | Hash (CLASSDATA) | All blocks in the chain, shared across all instances |
cJson | Character | JSON representation of the entire chain |
uDifficulty | Character | Mining difficulty prefix (default: "0000") |
nIterations | Numeric | Total mining iterations performed |
cPrivateKey | Character | Private key for signing blocks |
cPublicKey | Character | Public key for signature verification |
cSignature | Character | Block signature string |
Methods
| Method | Description |
|---|---|
New( cKey ) | Create a new blockchain with genesis block, keyed by cKey |
AddNewBlock( uOnce, cData ) | Add a new block with optional nonce and data string |
BlockToHash( nIdx, uOnce, cData ) | Compute the hash for a given block index and data |
MineBlock( nIdx ) | Mine block nIdx by iterating nonces until hash matches difficulty |
IsValidHash( nIdx ) | Check whether block nIdx has a valid hash matching difficulty |
IsValidBlock( nIdx, cHash ) | Validate block nIdx against the provided hash |
CountBlocks() | Return the total number of blocks in the chain |
UpdateAllBlocks() | Recompute hashes for all blocks in the chain |
Example: Creating a Chain
#include "FiveWin.ch"
function Main()
local oChain := TBlockChain():New( "myapp" )
// Add blocks with data
oChain:AddNewBlock( , "Genesis: Base record" )
oChain:AddNewBlock( , "Block 2: Transaction data" )
oChain:AddNewBlock( , "Block 3: Verification record" )
// Mine the second block
oChain:MineBlock( 2 )
// Validate
if oChain:IsValidHash( 2 )
MsgInfo( "Block 2 is valid. Total blocks: " + ;
Str( oChain:CountBlocks() ) )
endif
// Output chain as JSON
if ! Empty( oChain:cJson )
MemoWrit( "chain.json", oChain:cJson )
endif
oChain:End()
return nil
Notes
- The
aBlocksdata member is marked CLASSDATA and stored as a hash keyed by the cKey parameter passed to New(). All instances using the same key share the same chain data. - The default difficulty (
uDifficulty) is "0000", requiring the first four hex digits of the SHA-256 hash to be zero. Increase the string length (e.g. "000000") to make mining exponentially harder. MineBlock()increments the nonce and re-hashes until the hash matches the difficulty prefix. The number of iterations is accumulated innIterations.- Written by Cristobal Navarro.