Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Транзакции не объединяются в блоки, вместо этого транзакции закрепляются в определенной цепочке, после конкретной транзакции.
- // Tx determines the structure of the transaction.
- type Tx struct {
- Id Hash `json:"id"`
- SenderPublicKey Hash `json:"senderPublicKey"`
- SenderId Hash `json:"senderId"`
- RecipientId Hash `json:"recipientId"`
- Amount Coin `json:"amount"`
- Fee Coin `json:"fee"`
- Signature Hash `json:"signature"`
- Timestamp int64 `json:"timestamp"`
- Nonce uint32 `json:"nonce"`
- Height uint32 `json:"height"`
- Chain Hash `json:"chain"`
- PreviousTx Hash `json:"previousTx"`
- }
- // Process called directly for transaction processing.
- // Do not use this method to write to the chain, here only the results are processed.
- func (p *DefaultProcessor) Process(tx *types.Tx, ch *Chain) error {
- p.mup.Lock()
- defer p.mup.Unlock()
- recipient := p.am.Get(tx.RecipientId)
- recipient.Balance = types.NewCoin(recipient.Balance.Uint64() + tx.Amount.Uint64())
- recipient.LastTx = tx.Id
- senderPub := types.NewPublicKeyByHex(tx.SenderPublicKey.String())
- sender := p.am.GetByPublicKey(senderPub)
- sender.LastTx = tx.Id
- if senderPub.Address() == tx.SenderId.String() {
- sender.PublicKey = senderPub
- }
- balance := sender.Balance.Uint64() - (tx.Amount.Uint64() + tx.Fee.Uint64())
- sender.Balance = types.NewCoin(balance)
- err := p.am.Save(recipient)
- if err != nil {
- return err
- }
- err = p.am.Save(sender)
- if err != nil {
- return err
- }
- return p.am.Commit()
- }
- Вместо блоков используются снепшоты, которые синхронизируются со всеми членами сети(в отличии от самих транзакций). Снепшоты заключают в себя последние измененные балансы аккаунтов и информации о голосах.
- // SnapShot is an alternative to blocks, stores only the latest balances after
- // account changes and information on voting for delegates.
- //
- // It is the only synchronous chain that must be synchronized with all network members.
- type SnapShot struct {
- Version uint `json:"version"`
- Id types.Hash `json:"id"`
- Height uint32 `json:"height"`
- PreviousSnapShot types.Hash `json:"previousSnapShot"`
- GeneratorPublicKey types.Hash `json:"generatorPublicKey"`
- Votes []Vote `json:"votes"`
- Balances []Balance `json:"balances"`
- Timestamp int64 `json:"timestamp"`
- Signatures []Signature `json:"signaturess"`
- Signature types.Hash `json:"signature"`
- Nonce uint32 `json:"nonce"`
- mu sync.Mutex
- }
- // SnapShotFactory is releasing new snapshots for delegates.
- type SnapShotFactory struct {
- sm *SnapShotManager
- am *account.AccountManager
- ch *chain.ChainHelper
- interval time.Duration
- mu sync.Mutex
- running bool
- delegate *types.KeyPair
- }
- Алгоритм подписи на основе эллиптических кривых ed25519
- // Sign creates a signature for any element that Byteble implements.
- // Requires that you also specify generator and signature, where the public key
- // of the signer and his signature will be placed.
- // dataOffset will also help you delete the last n bytes of the byte array.
- func Sign(object interfaces.Byter, pair *types.KeyPair, generator *types.Hash,
- signature *types.Hash, dataOffset int) {
- // First of all, we need to change the generator field since
- // this can affect the data in the array.
- generatorHex := make([]byte, 64)
- pub := *pair.Public()
- hex.Encode(generatorHex, pub)
- *generator = generatorHex
- // Having received a set of bytes, we do not send the entire array for the
- // signature, only the hash.
- bytes := object.GetBytes()
- data := bytes[:len(bytes)-dataOffset]
- hashBytes := sha256.Sha256(data)
- secret := *pair.Secret()
- privateBytes := types.NewHash(secret).ToBytes()
- sign := ed25519.Sign(privateBytes, hashBytes)
- signHex := make([]byte, 128)
- hex.Encode(signHex, sign)
- *signature = signHex
- }
- // Verify verifies the validity of the generator signature by Byter object.
- // Unlike Sign does not require pointers.
- // For the validity of events, do not forget to specify the same dataOffset
- // when signing and verifying.
- func Verify(object interfaces.Byter, generator types.Hash,
- signature types.Hash, dataOffset int) bool {
- bytes := object.GetBytes()
- data := bytes[:len(bytes)-dataOffset]
- hashBytes := sha256.Sha256(data)
- sig := make([]byte, 64)
- gen := make([]byte, 32)
- hex.Decode(sig, signature.ToBytes())
- hex.Decode(gen, generator.ToBytes())
- return ed25519.Verify(gen, hashBytes, sig)
- }
- Пара ключей, обеспечивающая создание приватного и публичного ключа по seed и преобразования публичного ключа в адрес для получения монет.
- // KeyPair this is a pair of keys: private and public.
- type KeyPair struct {
- secret SecretKey
- public PublicKey
- }
- // Public is getter for public key.
- func (k *KeyPair) Public() *PublicKey {
- return &k.public
- }
- // NewKeyPair creates and returns a pointer to a key pair (public, private).
- func NewKeyPair(seed []byte) *KeyPair {
- hash := sha256.Sha256(seed)
- key := ed25519.NewKeyFromSeed(hash)
- publicKey := make([]byte, 32)
- copy(publicKey, key[32:])
- secretKey := make([]byte, 64)
- copy(secretKey[:32], hash)
- copy(secretKey[32:], publicKey)
- keypair := KeyPair{
- secretKey,
- publicKey,
- }
- return &keypair
- }
- // Secret is getter for private key.
- func (k KeyPair) Secret() *SecretKey {
- return &k.secret
- }
- // Address creates address by public key.
- func (k *PublicKey) Address() string {
- hash := sha256.Sha256(*k)
- ripemd := ripemd160.New()
- ripemd.Write(hash)
- sum := ripemd.Sum([]byte{})
- buffer := bytes.NewBuffer(nil)
- buffer.WriteString(utils.ADDR_PREFIX)
- buffer.Write(base58.Check(sum))
- return buffer.String()
- }
- // NewPublicKeyByHex creates a public key for the string representation.
- func NewPublicKeyByHex(s string) PublicKey {
- b, _ := hex.DecodeString(s)
- return PublicKey(b)
- }
- func HasAddr(addr []byte) bool {
- return len(addr) > 2 && addr[0] == 'B' && addr[1] == '0'
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement