Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Реализовать отправку и получение блоков между нодами #32

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ go.work

node_modules/
.DS_Store
chain_storage/
chain_storage*/
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ go run cmd/blockchain/main.go -address localhost:8080 -http localhost:8090 -stor

go run cmd/blockchain/main.go -address localhost:8081 -peers localhost:8080 -http localhost:8091 -storage chain_storage_2

go run cmd/blockchain/main.goo -address localhost:8082 -peers localhost:8080,localhost:8081 -http localhost:8092 -storage chain_storage_3
go run cmd/blockchain/main.go -address localhost:8082 -peers localhost:8080,localhost:8081 -http localhost:8092 -storage chain_storage_3
crazymidnight marked this conversation as resolved.
Show resolved Hide resolved
```

### Generate private key for testing
Expand Down
4 changes: 3 additions & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,19 @@ func (h *Handler) MineBlock(w http.ResponseWriter, r *http.Request) {
h.StatusesRWLock.Lock()
h.MiningStatuses[id] = MineStatusResponse{Status: StatusPending}
h.StatusesRWLock.Unlock()
err := h.Blockchain.MinePendingTransactions("")
block, err := h.Blockchain.MinePendingTransactions("")
if err != nil {
h.StatusesRWLock.Lock()
h.MiningStatuses[id] = MineStatusResponse{
Status: StatusFailed,
Details: fmt.Sprintf("Error: %v", err),
}
h.StatusesRWLock.Unlock()
return
}
h.StatusesRWLock.Lock()
h.MiningStatuses[id] = MineStatusResponse{Status: StatusSuccessful}
go h.Node.BroadcastBlock(block)
h.StatusesRWLock.Unlock()
}()
err := json.NewEncoder(w).Encode(MineResponse{Id: id.String()})
Expand Down
21 changes: 18 additions & 3 deletions chain/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,16 +273,28 @@ func (chain *Blockchain) IsValid() bool {
return true
}

func (chain *Blockchain) MinePendingTransactions(minerAddress string) error {
func (chain *Blockchain) MinePendingTransactions(minerAddress string) (Block, error) {
currentPoolSize := len(chain.PendingTransactions)
if currentPoolSize == 0 {
return Block{}, errors.New("Transaction pool is empty")
}

var transactions []Transaction

if currentPoolSize < chain.MaxBlockSize {
transactions = chain.PendingTransactions[0:currentPoolSize]
chain.PendingTransactions = chain.PendingTransactions[currentPoolSize:]
err := chain.Storage.DequeueTransactions(currentPoolSize)
if err != nil {
fmt.Println("Could not dequeue transactions from storage")
}
} else {
transactions = chain.PendingTransactions[0 : chain.MaxBlockSize-1]
chain.PendingTransactions = chain.PendingTransactions[chain.MaxBlockSize-1:]
err := chain.Storage.DequeueTransactions(chain.MaxBlockSize - 1)
if err != nil {
fmt.Println("Could not dequeue transactions from storage")
}
}

rewardTx := Transaction{
Expand All @@ -302,20 +314,23 @@ func (chain *Blockchain) MinePendingTransactions(minerAddress string) error {
}
block.Hash = block.CalculateHash()

// TODO: sync transaction removal between nodes
// TODO: recover if mining failed
block.MineBlock(chain.Difficulty)
chain.AddBlock(block)
err := chain.Storage.AddBlock(block)
if err != nil {
return err
return Block{}, err
}
return nil
return block, nil
}

type Storage interface {
Load(difficulty, maxBlockSize int, miningReward float64) (*Blockchain, error)
AddBlock(b Block) error
AddTransaction(t Transaction) error
Reset(chain *Blockchain) error
DequeueTransactions(n int) error
}

func InitBlockchain(difficulty, maxBlockSize int, miningReward float64, s Storage) *Blockchain {
Expand Down
1 change: 1 addition & 0 deletions cmd/private_key_generator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ func main() {
wallet := chain.Wallet{}
wallet.KeyGen()
fmt.Println(wallet.PrivateKey)
fmt.Println(wallet.PublicKey)
t := chain.Transaction{}
err := t.Sign(wallet.PrivateKey)
if err != nil {
Expand Down
17 changes: 13 additions & 4 deletions frontend/src/AddTransactionModalButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,23 @@ import {

import AddTransactionForm from './AddTransactionForm'

export default function AddTransactionsModalButton() {
const { isOpen, onOpen, onClose } = useDisclosure()
interface AddTransactionsModalButtonProps {
onClose: () => void;
}

export default function AddTransactionsModalButton({ onClose }: AddTransactionsModalButtonProps) {
const { isOpen, onOpen, onClose: closeModal } = useDisclosure()

const handleClose = () => {
closeModal();
onClose();
};

return (
<>
<Button onClick={onOpen}>Add Transaction</Button>

<Modal isOpen={isOpen} onClose={onClose} size={'full'}>
<Modal isOpen={isOpen} onClose={handleClose} size={'full'}>
<ModalOverlay />
<ModalContent>
<ModalCloseButton />
Expand All @@ -39,7 +48,7 @@ export default function AddTransactionsModalButton() {
</ModalBody>

<ModalFooter>
<Button colorScheme='blue' mr={3} onClick={onClose}>
<Button colorScheme='blue' mr={3} onClick={handleClose}>
Close
</Button>
</ModalFooter>
Expand Down
10 changes: 7 additions & 3 deletions frontend/src/TransactionsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,21 @@ async function fetchTransactions(): Promise<TransactionProps[]> {
}

export default function TransactionsPage({ caption }: { caption: string }) {
const { isPending, error, data } = useQuery({
const { isPending, error, data, refetch } = useQuery({
queryKey: ["transactions"],
queryFn: fetchTransactions,
});

const handleRefetch = () => {
refetch();
};

if (!data || !data.length) {
return (
<>
<>No transactions yet.</>
<Flex justifyContent={"flex-end"} my={6}>
<AddTransactionsModalButton />
<AddTransactionsModalButton onClose={handleRefetch} />
</Flex>
</>
);
Expand All @@ -34,7 +38,7 @@ export default function TransactionsPage({ caption }: { caption: string }) {
<>
<TransactionsTable caption={caption} transactions={data} />
<Flex justifyContent={"flex-end"} my={6}>
<AddTransactionsModalButton />
<AddTransactionsModalButton onClose={handleRefetch} />
</Flex>
</>
);
Expand Down
27 changes: 27 additions & 0 deletions storage/badger.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,33 @@ func (bs *Storage) AddTransaction(t chain.Transaction) error {
return err
}

func (bs *Storage) DequeueTransactions(n int) error {
return bs.db.Update(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()

prefix := []byte(transactionPrefix)
count := 0

for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
if count >= n {
break
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мб nil сразу вернуть. Как ниже возврат ошибки

}

key := it.Item().Key()
if err := txn.Delete(key); err != nil {
return err
}

count++
}

return nil
})
}

func (storage *Storage) deleteByPrefix(prefix []byte) error {
deleteKeys := func(keysForDelete [][]byte) error {
if err := storage.db.Update(func(txn *badger.Txn) error {
Expand Down
Loading