zkt24/z2/backend/main.go

218 lines
5.9 KiB
Go
Raw Normal View History

2024-04-25 11:51:47 +00:00
package main
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"log"
"sync"
// "crypto/rand"
"thesis/core"
"thesis/crypto"
"thesis/db"
"thesis/ent"
"thesis/rpc"
"time"
_ "github.com/mattn/go-sqlite3"
blst "github.com/supranational/blst/bindings/go"
mt "github.com/txaty/go-merkletree"
)
type Transaction = core.Transaction
// func generateRandBlocks(size int) (blocks []mt.DataBlock) {
// for i := 0; i < size; i++ {
// block := &Transaction{
// data: make([]byte, 100),
// }
// _, err := rand.Read(block.data)
// handleError(err)
// blocks = append(blocks, block)
// }
// return
// }
// func merklePOC() {
// blocks := generateRandBlocks(5)
// tree, err := mt.New(nil, blocks)
// handleError(err)
// proofs := tree.Proofs
// for i := 0; i < len(proofs); i++ {
// ok, err := tree.Verify(blocks[i], proofs[i])
// handleError(err)
// fmt.Println(ok)
// }
// rootHash := tree.Root
// for i := 0; i < len(blocks); i++ {
// ok, err := mt.Verify(blocks[i], proofs[i], rootHash, nil)
// handleError(err)
// fmt.Println(ok)
// }
// }
func generateRandData(client *ent.Client, sk *blst.SecretKey, pk string, n int) {
signerKey, err := client.Key.Create().SetPublicKey(pk).SetOwner("gensis miner").Save(context.Background())
handleError(err)
var blocks []mt.DataBlock
for i := 0; i < n; i++ {
txContent := &core.TransactionContent{
Signer: "0x0deadbeef",
Commitment: "0x0000",
}
contentBytes, err := json.Marshal(txContent)
handleError(err)
var tx *core.Transaction
if i == 0 {
tx = &core.Transaction{
Type: i,
Timestamp: time.Now().Unix(),
Comment: "The gensis block",
Content: contentBytes,
}
} else {
tx = &core.Transaction{
Type: 2,
Timestamp: time.Now().Unix(),
Comment: "dummy block",
Content: contentBytes,
}
}
txBytes, err := json.Marshal(tx)
handleError(err)
hash := sha256.New()
hash.Write(txBytes)
tx.Hash = fmt.Sprintf("0x%x", string(hash.Sum(nil)))
tx.Signature = crypto.SignMessage(tx.Hash, sk)
// fmt.Println("The signature is", tx.Signature)
// fmt.Println(string(tx.Signature))
txDB := db.AddTx(client, tx, signerKey)
txBytes, err = json.Marshal(tx)
handleError(err)
hash = sha256.New()
hash.Write(txBytes)
var block core.Block
if i == 0 {
block = core.Block{
Hash: fmt.Sprintf("0x%x", string(hash.Sum(nil))),
Nonce: i,
Length: 1,
PreviousHash: "0x000",
}
} else {
// lastBlock, err := client.Blocks.Query().Order(ent.Desc()).All(context.Background()) //Only(context.Background())
// handleError(err)
lastHash, err := blocks[len(blocks)-1].Serialize()
handleError(err)
block = core.Block{
Hash: fmt.Sprintf("0x%x", string(hash.Sum(nil))),
Nonce: i,
Length: 1,
PreviousHash: string(lastHash), //lastBlock[0].Hash,
}
}
// fmt.Printf("0x%x", string(tx.Signature))
blockDB := db.AddBlock(client, &block)
txDB.Update().AddBlock(blockDB).Save(context.Background())
blocks = append(blocks, block)
}
tree, err := mt.New(nil, blocks)
handleError(err)
proofs := tree.Proofs
for i := 0; i < len(proofs); i++ {
ok, err := tree.Verify(blocks[i], proofs[i])
handleError(err)
fmt.Println(ok)
}
rootHash := tree.Root
for i := 0; i < len(blocks); i++ {
ok, err := mt.Verify(blocks[i], proofs[i], rootHash, nil)
handleError(err)
fmt.Println(ok)
}
fmt.Printf("Root Hash: 0x%x", rootHash)
}
func main() {
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
// client, err := ent.Open("sqlite3", "file:chaindb?cache=shared&_fk=1")
handleError(err)
defer client.Close()
// // keys.GenerateKeys()
// sk, _ := crypto.ImportKeyFromHex("0x2ed682681702cddf5b9cd4f26a95c78953bfa1058a76aae69cc1aa0bb9bb3c5b")
// pk := new(crypto.PublicKey).From(sk)
// // Run the auto migration tool.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
// core.ValidateContent(client, pk)
// server := true
// generateRandData(client, sk, string(pk.Compress()), 30)
// testSk, _ := crypto.ImportKeyFromHex("0x328c8bdb0a70df287e8241b93f75bba446d1b7a3cbc8b1b0eebbb9e856e83cff")
// pk := new(crypto.PublicKey).From(testSk)
// encodePk := hex.EncodeToString(pk.Compress())
// fmt.Println(encodePk)
// testPub := "b82ab3d1841afc7d9b65ee31cb38f82d5d177231f05edc93e01a74f1d3151503ee37eda7d2093122b725d37ffbda2098"
// testSig := "99a734d2bf5c509f9651992725a2c3ea43bd33621bb177317664bc4c3aebbfef58f401605134a6c9349bf7fb918177b706ed1a97e4fc92ab0a0813e7bd96e5fadbf10446f32cbf314337a59c1372f6b944e12eb1c0f3b2dae5dd9393a6c75d71"
// testPubBytes, err := hex.DecodeString(testPub)
// handleError(err)
// testPk := new(crypto.PublicKey).Uncompress(testPubBytes)
// fmt.Println(hex.EncodeToString(testPk.Compress()))
// hash, err := hex.DecodeString("a47cb1f3c9f8066549b30ef863f4ce919d089c7d3d1c779ea28cdb8fdf7bb1c5")
// handleError(err)
// err = crypto.ValidateSignature(testSig, testPk, hash)
// if err == nil {
// fmt.Println("woop we got it man")
// } else {
// fmt.Println("invalid")
// }
// client.Transactions.Create().SetType()
// blocks := []mt.DataBlock{block}
// ctx, cancel := context.WithCancel(context.Background())
// defer cancel()
// node := p2p.StartNode(0)
// if server {
// p2p.StartListener(ctx, node)
// <-ctx.Done()
// } else {
// txContent := &core.TransactionContent{
// Signer: "0x0deadbeef",
// Commitment: "0x0000",
// }
// contentBytes, err := json.Marshal(txContent)
// contentBytes = append(contentBytes, []byte("\n")...)
// handleError(err)
// p2p.RunSender(ctx, node, "/ip4/127.0.0.1/tcp/40125/p2p/12D3KooWFKjCej7sXzgV2hcYvDtPBsB66mg6WwjacGUMpF6spe8X", contentBytes)
// }
var wg sync.WaitGroup
wg.Add(1)
go rpc.Serve(&wg, client)
wg.Wait()
}
func handleError(err error) {
if err != nil {
panic(err)
}
}