lbcwallet/wallet/txauthor/cprng.go

40 lines
852 B
Go
Raw Normal View History

Refactor wallet transaction creation code. This began as a change to improve the fee calculation code and evolved into a much larger refactor which improves the readability and modularity of all of the transaction creation code. Transaction fee calculations have been switched from full increments of the relay fee to a proportion based on the transaction size. This means that for a relay fee of 1e3 satoshis/kB, a 500 byte transaction is only required to pay a 5e2 satoshi fee and a 1500 byte transaction only need pay a 1.5e3 fee. The previous code would end up estimating these fees to be 1e3 and 2e3 respectively. Because the previous code would add more fee than needed in almost every case, the transaction size estimations were optimistic (best/smallest case) and signing was done in a loop where the fee was incremented by the relay fee again each time the actual size of the signed transaction rendered the fee too low. This has switched to using worst case transaction size estimates rather than best case, and signing is only performed once. Transaction input signature creation has switched from using txscript.SignatureScript to txscript.SignTxOutput. The new API is able to redeem outputs other than just P2PKH, so the previous restrictions about P2SH outputs being unspendable (except through the signrawtransaction RPC) no longer hold. Several new public packages have been added: wallet/txauthor - transaction authoring and signing wallet/txfees - fee estimations and change output inclusion wallet/txrules - simple consensus and mempool policy rule checks Along with some internal packages: wallet/internal/txsizes - transaction size estimation internal/helpers - context free convenience functions The txsizes package is internal as the estimations it provides are specific for the algorithms used by these new packages.
2016-02-28 05:30:56 +01:00
// Copyright (c) 2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package txauthor
import (
"crypto/rand"
"encoding/binary"
mrand "math/rand"
"sync"
)
// cprng is a cryptographically random-seeded math/rand prng. It is seeded
// during package init. Any initialization errors result in panics. It is safe
// for concurrent access.
var cprng = cprngType{}
type cprngType struct {
r *mrand.Rand
mu sync.Mutex
}
func init() {
buf := make([]byte, 8)
_, err := rand.Read(buf)
if err != nil {
panic("Failed to seed prng: " + err.Error())
}
seed := int64(binary.LittleEndian.Uint64(buf))
cprng.r = mrand.New(mrand.NewSource(seed))
}
func (c *cprngType) Int31n(n int32) int32 {
defer c.mu.Unlock() // Int31n may panic
c.mu.Lock()
return c.r.Int31n(n)
}