66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
|
package db
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
|
||
|
"thesis/core"
|
||
|
"thesis/ent"
|
||
|
"thesis/ent/key"
|
||
|
)
|
||
|
|
||
|
func AddTx(client *ent.Client, tx *core.Transaction, signerKey *ent.Key) *ent.Transactions {
|
||
|
dbtx, err := client.Transactions.Create().
|
||
|
SetType(tx.Type).
|
||
|
SetTimestamp(int(tx.Timestamp)).
|
||
|
SetComment(tx.Comment).
|
||
|
SetContent(tx.Content).
|
||
|
SetHash(tx.Hash).
|
||
|
SetSignature(tx.Signature).AddSigner(signerKey).Save(context.Background())
|
||
|
|
||
|
handleError(err)
|
||
|
return dbtx
|
||
|
}
|
||
|
|
||
|
func AddBlock(client *ent.Client, block *core.Block) *ent.Blocks {
|
||
|
dbBlock, err := client.Blocks.Create().
|
||
|
SetHash(block.Hash).
|
||
|
SetID(block.Nonce).
|
||
|
SetLength(block.Length).
|
||
|
SetPreviousHash(block.PreviousHash).
|
||
|
Save(context.Background())
|
||
|
handleError(err)
|
||
|
return dbBlock
|
||
|
}
|
||
|
|
||
|
func AddKey(client *ent.Client, pk string, owner string) error {
|
||
|
_, err := client.Key.Create().SetPublicKey(pk).SetOwner(owner).Save(context.Background())
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
func GetKeyFromHex(client *ent.Client, pk string) *ent.Key {
|
||
|
k, err := client.Key.Query().Where(key.PublicKeyEQ(pk)).All(context.Background())
|
||
|
handleError(err)
|
||
|
return k[0]
|
||
|
}
|
||
|
|
||
|
func GetTxCount(client *ent.Client) int {
|
||
|
count, err := client.Transactions.Query().Count(context.Background())
|
||
|
handleError(err)
|
||
|
return count
|
||
|
}
|
||
|
|
||
|
func GetLatestBlock(client *ent.Client) *ent.Blocks {
|
||
|
blocks, err := client.Blocks.Query().All(context.Background())
|
||
|
handleError(err)
|
||
|
if len(blocks) == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
return blocks[len(blocks)-1]
|
||
|
}
|
||
|
|
||
|
func handleError(err error) {
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
}
|