Skip to content

Instantly share code, notes, and snippets.

@bigjonroberts
Last active December 18, 2017 08:19
Show Gist options
  • Save bigjonroberts/77b54361d2f39eda964a16ec2787359d to your computer and use it in GitHub Desktop.
Save bigjonroberts/77b54361d2f39eda964a16ec2787359d to your computer and use it in GitHub Desktop.
port of snakecoin.py to F#
#load @"..\.paket\load\netstandard2.0\main.group.fsx"
// Define what an FsCoin block is
type Block = {
Index: int64
Timestamp: NodaTime.Instant
Data: string
PreviousHash: string } with
member x.Hash =
use sha256 = System.Security.Cryptography.SHA256.Create()
System.Text.Encoding.ASCII.GetBytes (x.Index.ToString() + x.Timestamp.ToString() + x.Data.ToString() + x.PreviousHash)
|> sha256.ComputeHash
|> System.BitConverter.ToString |> fun s -> s.Replace("-", System.String.Empty)
// Generate all later blocks in the blockchain
let nextBlock (lastBlock:Block) =
let newIndex = lastBlock.Index + 1L
{ Index = newIndex
Timestamp = NodaTime.SystemClock.Instance.GetCurrentInstant()
Data = sprintf "Hey! I'm block %i" newIndex
PreviousHash = lastBlock.Hash }
let rec genBlocks groupsize chain = seq {
match groupsize with
| n when n <= 0 -> ()
| n -> let b = Array.last chain |> nextBlock
yield b
yield! genBlocks (n-1) (Array.append chain [|b|]) }
// Create the blockchain and add the genesis block
let blockchain =
// Manually construct a block with
// index zero and arbitrary previous hash
{ Index = 0L; Timestamp = NodaTime.SystemClock.Instance.GetCurrentInstant(); Data = "Genesis Block"; PreviousHash = "0" }
|> Array.singleton
// Add blocks to the chain
genBlocks 20 blockchain
// Tell everyone about it!
|> Seq.map (fun (b:Block) ->
printfn "Block %i has been added to the blockchain!" b.Index
printfn "Hash: %s" b.Hash
b )
|> Seq.toArray
|> Array.append blockchain
source https://api.nuget.org/v3/index.json
source https://www.myget.org/F/test-paket/api/v2
nuget FSharp.Core
nuget System.Security.Cryptography.Algorithms
nuget NodaTime
FSharp.Core
System.Security.Cryptography.Algorithms
NodaTime
@bigjonroberts
Copy link
Author

@michalkovy Thanks, I implemented your suggestion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment