TBlockChain

Fuente: 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

DATATypeDescription
aBlocksHash (CLASSDATA)All blocks in the chain, shared across all instances
cJsonCharacterJSON representation of the entire chain
uDifficultyCharacterMining difficulty prefix (default: "0000")
nIterationsNumericTotal mining iterations performed
cPrivateKeyCharacterPrivate key for signing blocks
cPublicKeyCharacterPublic key for signature verification
cSignatureCharacterBlock signature string

Methods

MethodDescription
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

Ver También