Skip to content

Commit

Permalink
add: Added Modules System
Browse files Browse the repository at this point in the history
  • Loading branch information
pred695 committed Apr 18, 2024
1 parent f0e7758 commit 7f23e59
Show file tree
Hide file tree
Showing 24 changed files with 409 additions and 15,274 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.vscode/*
go.sum
vendor/
output.txt
/*.txt
47 changes: 47 additions & 0 deletions Blockchain/mine.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package Blockchain

import (
"encoding/hex"
"fmt"
"os"
"time"

"github.com/pred695/code-challenge-2024-pred695/Structs"
"github.com/pred695/code-challenge-2024-pred695/Utils"
)

var Bh Structs.BlockHeader = Structs.BlockHeader{
Version: 7,
PrevBlockHash: "0000000000000000000000000000000000000000000000000000000000000000",
MerkleRoot: "",
Time: time.Now().Unix(),
Bits: 0x1f00ffff,
Nonce: 0,
}

func MineBlock() {
netReward, TxIDs, _ := Utils.Prioritize()

cbTx := Utils.CreateCoinbase(netReward)
serializedcbTx, _ := Utils.SerializeTransaction(cbTx)
fmt.Printf("CBTX: %x\n", serializedcbTx)
TxIDs = append([]string{hex.EncodeToString(Utils.ReverseBytes(Utils.To_sha(Utils.To_sha(serializedcbTx))))}, TxIDs...)
mkr := Utils.NewMerkleTree(TxIDs)
Bh.MerkleRoot = hex.EncodeToString(mkr.Data)
cbtxbase := Utils.CalculateBaseSize(cbTx)
cbtxwitness := Utils.CalculateWitnessSize(cbTx)
fmt.Println("Cbtx wt: ", cbtxwitness+(cbtxbase*4))
if ProofOfWork(&Bh) {
file, _ := os.Create("output.txt")
defer file.Close()
// fmt.Println(Bh.merkleRoot)
// fmt.Println(Bh.nonce)
serializedBh := Utils.SerializeBlockHeader(&Bh)
segserialized, _ := Utils.SegWitSerialize(cbTx)
file.WriteString(hex.EncodeToString(serializedBh) + "\n")
file.WriteString(hex.EncodeToString(segserialized) + "\n")
for _, tx := range TxIDs {
file.WriteString(tx + "\n")
}
}
}
46 changes: 46 additions & 0 deletions Blockchain/pow.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package Blockchain

import (
"encoding/hex"
"fmt"

"github.com/pred695/code-challenge-2024-pred695/Structs"
"github.com/pred695/code-challenge-2024-pred695/Utils"
)

const target string = "0000ffff00000000000000000000000000000000000000000000000000000000"

func CompareByteArrays(a, b []byte) int {
if len(a) != len(b) {
panic("Arrays must have the same length")
}

for i := range a {
if a[i] < b[i] {
return -1
} else if a[i] > b[i] {
return 1
}
}

return 0
}

func ProofOfWork(bh *Structs.BlockHeader) bool {
targetBytes, _ := hex.DecodeString(target)
// fmt.Printf("Target: %v\n", targetBytes)
for {
serialized := Utils.SerializeBlockHeader(bh)
hash := Utils.ReverseBytes(Utils.To_sha(Utils.To_sha(serialized)))

if CompareByteArrays(hash, targetBytes) == -1 {
fmt.Println("Block Mined", hex.EncodeToString(hash))
return true
}
if bh.Nonce < 0x0 || bh.Nonce > 0xffffffff {
fmt.Println("FUCKED")
return false
}
bh.Nonce++
}
}
61 changes: 61 additions & 0 deletions Structs/struct.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package Structs


type BlockHeader struct {
Version uint32
PrevBlockHash string
MerkleRoot string
Time int64
Bits uint32
Nonce uint32
}


type Input struct {
TxID string `json:"txid"`
Vout uint32 `json:"vout"`
Prevout Prevout `json:"prevout"`
Scriptsig string `json:"scriptsig"`
ScriptsigAsm string `json:"scriptsig_asm"`
Witness []string `json:"witness"`
IsCoinbase bool `json:"is_coinbase"`
Sequence uint32 `json:"sequence"`
}

type Prevout struct {
Scriptpubkey string `json:"scriptpubkey"`
ScriptpubkeyAsm string `json:"scriptpubkey_asm"`
ScriptpubkeyType string `json:"scriptpubkey_type"`
ScriptpubkeyAddress string `json:"scriptpubkey_address"`
Value uint64 `json:"value"`
}

type Transaction struct {
Version uint32 `json:"version"`
Locktime uint32 `json:"locktime"`
Vin []Input `json:"vin"`
Vout []Prevout `json:"vout"`
}

type TxInfo struct {
TxID string
WTxID string
Fee uint64
Weight uint64
}
type TxWeight struct {
BaseSize int `json:"base_size"` // Size of non-witness data in bytes
WitnessSize int `json:"witness_size"` // Size of witness data in bytes
Weight int `json:"weight"` // Total weight in weight units
}


type MerkleNode struct {
Left *MerkleNode
Data []byte
Right *MerkleNode
}

type MerkleTree struct {
MerkleRoot *MerkleNode
}
14 changes: 8 additions & 6 deletions coinbase.go → Utils/coinbase.go
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package main
package Utils

func Coinbase(netReward uint64) *Transaction {
import "github.com/pred695/code-challenge-2024-pred695/Structs"

func CreateCoinbase(netReward uint64) *Structs.Transaction {
witnessCommitment := CreateWitnessMerkle()
coinbaseTx := Transaction{
coinbaseTx := Structs.Transaction{
Version: 1,
Vin: []Input{
Vin: []Structs.Input{
{
TxID: "0000000000000000000000000000000000000000000000000000000000000000",
Vout: 0xffffffff,
Prevout: Prevout{
Prevout: Structs.Prevout{
Scriptpubkey: "0014df4bf9f3621073202be59ae590f55f42879a21a0",
ScriptpubkeyAsm: "0014df4bf9f3621073202be59ae590f55f42879a21a0",
ScriptpubkeyType: "p2pkh",
Expand All @@ -21,7 +23,7 @@ func Coinbase(netReward uint64) *Transaction {
Witness: []string{"0000000000000000000000000000000000000000000000000000000000000000"},
},
},
Vout: []Prevout{
Vout: []Structs.Prevout{
{
Scriptpubkey: "0014df4bf9f3621073202be59ae590f55f42879a21a0",
ScriptpubkeyAsm: "0014df4bf9f3621073202be59ae590f55f42879a21a0",
Expand Down
59 changes: 59 additions & 0 deletions Utils/merkle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package Utils

import (
"encoding/hex"
"fmt"

"github.com/pred695/code-challenge-2024-pred695/Structs"
)

func NewMerkleNode(lnode *Structs.MerkleNode, rnode *Structs.MerkleNode, data []byte) *Structs.MerkleNode {
var mNode Structs.MerkleNode = Structs.MerkleNode{}
if lnode == nil && rnode == nil {
//hash256 of the data
mNode.Data = ReverseBytes(data)
} else {
var prevHash []byte = append(lnode.Data, rnode.Data...)
mNode.Data = To_sha(To_sha(prevHash))
}
mNode.Left = lnode
mNode.Right = rnode
return &mNode
}

func NewMerkleTree(leaves []string) *Structs.MerkleNode {
var nodes []Structs.MerkleNode

for _, leaf := range leaves {
data, _ := hex.DecodeString(leaf)
var node Structs.MerkleNode = *NewMerkleNode(nil, nil, data)
nodes = append(nodes, node)
}

for len(nodes) > 1 {
var newLevel []Structs.MerkleNode
for i := 0; i < len(nodes); i += 2 {
// Handle case where the total number of nodes is odd.
if len(nodes)%2 != 0 {
nodes = append(nodes, nodes[len(nodes)-1])
}
node := *NewMerkleNode(&nodes[i], &nodes[i+1], nil)
newLevel = append(newLevel, node)
}
nodes = newLevel
}
return &nodes[0]

}

func CreateWitnessMerkle() string {
_, _, wTxIDs := Prioritize()
wTxIDs = append([]string{"0000000000000000000000000000000000000000000000000000000000000000"}, wTxIDs...)
merkleRoot := NewMerkleTree(wTxIDs)
fmt.Println("WMKR: ", hex.EncodeToString(merkleRoot.Data))
commitment_string := hex.EncodeToString(merkleRoot.Data) + "0000000000000000000000000000000000000000000000000000000000000000"
WitnessCommitment, _ := hex.DecodeString(commitment_string)
WitnessCommitment = To_sha(To_sha(WitnessCommitment))
fmt.Println("Witness Commitment: ", hex.EncodeToString(WitnessCommitment))
return hex.EncodeToString(WitnessCommitment)
}
31 changes: 13 additions & 18 deletions Prioritize.go → Utils/prioritize.go
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,33 +1,28 @@
package main
package Utils

import (
"encoding/hex"
"encoding/json"
"fmt"
"os"
"sort"
)

type TxInfo struct {
TxID string
WTxID string
Fee uint64
Weight uint64
}
"github.com/pred695/code-challenge-2024-pred695/Structs"
)

func comp(a, b TxInfo) bool {
func Comp(a, b Structs.TxInfo) bool {
return float64(a.Fee)/float64(a.Weight) > float64(b.Fee)/float64(b.Weight)
}
func Prioritize() (uint64, []string, []string) {
var permittedTxIDs []string
var permittedWTxIDs []string
dir := "./mempool"
files, _ := os.ReadDir(dir)
var txInfo []TxInfo
var txInfo []Structs.TxInfo
for _, file := range files {
txData, err := jsonData(dir + "/" + file.Name())
txData, err := JsonData(dir + "/" + file.Name())
Handle(err)
var tx Transaction
var tx Structs.Transaction
err = json.Unmarshal([]byte(txData), &tx)
var fee uint64 = 0
for _, vin := range tx.Vin {
Expand All @@ -36,17 +31,17 @@ func Prioritize() (uint64, []string, []string) {
for _, vout := range tx.Vout {
fee -= vout.Value
}
serialized, _ := serializeTransaction(&tx)
serialized, _ := SerializeTransaction(&tx)
segserialized, _ := SegWitSerialize(&tx)
txID := reverseBytes(to_sha(to_sha(serialized)))
wtxID := reverseBytes(to_sha(to_sha(segserialized)))
txInfo = append(txInfo, TxInfo{TxID: hex.EncodeToString(txID), WTxID: hex.EncodeToString(wtxID), Fee: fee, Weight: uint64(calculateWitnessSize(&tx) + CalculateBaseSize(&tx)*4)})
txID := ReverseBytes(To_sha(To_sha(serialized)))
wtxID := ReverseBytes(To_sha(To_sha(segserialized)))
txInfo = append(txInfo, Structs.TxInfo{TxID: hex.EncodeToString(txID), WTxID: hex.EncodeToString(wtxID), Fee: fee, Weight: uint64(CalculateWitnessSize(&tx) + CalculateBaseSize(&tx)*4)})

}
sort.Slice(txInfo, func(i, j int) bool {
return comp(txInfo[i], txInfo[j])
return Comp(txInfo[i], txInfo[j])
})
var PermissibleTxs []TxInfo
var PermissibleTxs []Structs.TxInfo
var PermissibleWeight uint64 = 3999300
var reward uint64 = 0
for _, tx := range txInfo {
Expand Down
Loading

0 comments on commit 7f23e59

Please sign in to comment.