本文整理匯總了Golang中github.com/roasbeef/btcd/btcec.S256函數的典型用法代碼示例。如果您正苦於以下問題:Golang S256函數的具體用法?Golang S256怎麽用?Golang S256使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了S256函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: BenchmarkPathPacketConstruction
func BenchmarkPathPacketConstruction(b *testing.B) {
route := make([]*btcec.PublicKey, NumMaxHops)
for i := 0; i < NumMaxHops; i++ {
privKey, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
b.Fatalf("unable to generate key: %v", privKey)
}
route[i] = privKey.PubKey()
}
var (
err error
sphinxPacket *OnionPacket
)
var hopPayloads [][]byte
for i := 0; i < len(route); i++ {
payload := bytes.Repeat([]byte{byte('A' + i)}, HopPayloadSize)
hopPayloads = append(hopPayloads, payload)
}
d, _ := btcec.PrivKeyFromBytes(btcec.S256(), bytes.Repeat([]byte{'A'}, 32))
for i := 0; i < b.N; i++ {
sphinxPacket, err = NewOnionPacket(route, d, hopPayloads, nil)
if err != nil {
b.Fatalf("unable to create packet: %v", err)
}
}
s = sphinxPacket
}
示例2: TestSigCacheAddMaxEntriesZeroOrNegative
// TestSigCacheAddMaxEntriesZeroOrNegative tests that if a sigCache is created
// with a max size <= 0, then no entries are added to the sigcache at all.
func TestSigCacheAddMaxEntriesZeroOrNegative(t *testing.T) {
// Create a sigcache that can hold up to 0 entries.
sigCache := NewSigCache(0)
// Generate a random sigCache entry triplet.
msg1, sig1, key1, err := genRandomSig()
if err != nil {
t.Errorf("unable to generate random signature test data")
}
// Add the triplet to the signature cache.
sigCache.Add(*msg1, sig1, key1)
// The generated triplet should not be found.
sig1Copy, _ := btcec.ParseSignature(sig1.Serialize(), btcec.S256())
key1Copy, _ := btcec.ParsePubKey(key1.SerializeCompressed(), btcec.S256())
if sigCache.Exists(*msg1, sig1Copy, key1Copy) {
t.Errorf("previously added signature found in sigcache, but" +
"shouldn't have been")
}
// There shouldn't be any entries in the sigCache.
if len(sigCache.validSigs) != 0 {
t.Errorf("%v items found in sigcache, no items should have"+
"been added", len(sigCache.validSigs))
}
}
示例3: fetchChanCommitKeys
func fetchChanCommitKeys(nodeChanBucket *bolt.Bucket, channel *OpenChannel) error {
// Construct the key which stores the commitment keys: ckk || channelID.
// TODO(roasbeef): factor into func
var bc bytes.Buffer
if err := writeOutpoint(&bc, channel.ChanID); err != nil {
return err
}
commitKey := make([]byte, len(commitKeys)+bc.Len())
copy(commitKey[:3], commitKeys)
copy(commitKey[3:], bc.Bytes())
var err error
keyBytes := nodeChanBucket.Get(commitKey)
channel.TheirCommitKey, err = btcec.ParsePubKey(keyBytes[:33], btcec.S256())
if err != nil {
return err
}
channel.OurCommitKey, err = btcec.ParsePubKey(keyBytes[33:], btcec.S256())
if err != nil {
return err
}
return nil
}
示例4: isPubKey
// isPubKey returns whether or not the passed public key script is a standard
// pay-to-pubkey script that pays to a valid compressed or uncompressed public
// key along with the serialized pubkey it is paying to if it is.
//
// NOTE: This function ensures the public key is actually valid since the
// compression algorithm requires valid pubkeys. It does not support hybrid
// pubkeys. This means that even if the script has the correct form for a
// pay-to-pubkey script, this function will only return true when it is paying
// to a valid compressed or uncompressed pubkey.
func isPubKey(script []byte) (bool, []byte) {
// Pay-to-compressed-pubkey script.
if len(script) == 35 && script[0] == txscript.OP_DATA_33 &&
script[34] == txscript.OP_CHECKSIG && (script[1] == 0x02 ||
script[1] == 0x03) {
// Ensure the public key is valid.
serializedPubKey := script[1:34]
_, err := btcec.ParsePubKey(serializedPubKey, btcec.S256())
if err == nil {
return true, serializedPubKey
}
}
// Pay-to-uncompressed-pubkey script.
if len(script) == 67 && script[0] == txscript.OP_DATA_65 &&
script[66] == txscript.OP_CHECKSIG && script[1] == 0x04 {
// Ensure the public key is valid.
serializedPubKey := script[1:66]
_, err := btcec.ParsePubKey(serializedPubKey, btcec.S256())
if err == nil {
return true, serializedPubKey
}
}
return false, nil
}
示例5: DeriveRevocationPubkey
// DeriveRevocationPubkey derives the revocation public key given the
// counter-party's commitment key, and revocation pre-image derived via a
// pseudo-random-function. In the event that we (for some reason) broadcast a
// revoked commitment transaction, then if the other party knows the revocation
// pre-image, then they'll be able to derive the corresponding private key to
// this private key by exploting the homomorphism in the elliptic curve group:
// * https://en.wikipedia.org/wiki/Group_homomorphism#Homomorphisms_of_abelian_groups
//
// The derivation is performed as follows:
//
// revokeKey := commitKey + revokePoint
// := G*k + G*h
// := G * (k+h)
//
// Therefore, once we divulge the revocation pre-image, the remote peer is able to
// compute the proper private key for the revokeKey by computing:
// revokePriv := commitPriv + revokePreimge mod N
//
// Where N is the order of the sub-group.
func DeriveRevocationPubkey(commitPubKey *btcec.PublicKey,
revokePreimage []byte) *btcec.PublicKey {
// First we need to convert the revocation hash into a point on the
// elliptic curve.
revokePointX, revokePointY := btcec.S256().ScalarBaseMult(revokePreimage)
// Now that we have the revocation point, we add this to their commitment
// public key in order to obtain the revocation public key.
revokeX, revokeY := btcec.S256().Add(commitPubKey.X, commitPubKey.Y,
revokePointX, revokePointY)
return &btcec.PublicKey{X: revokeX, Y: revokeY}
}
示例6: establishTestConnection
func establishTestConnection() (net.Conn, net.Conn, error) {
// First, generate the long-term private keys both ends of the connection
// within our test.
localPriv, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, nil, err
}
remotePriv, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
return nil, nil, err
}
// Having a port of ":0" means a random port, and interface will be
// chosen for our listener.
addr := ":0"
// Our listener will be local, and the connection remote.
listener, err := NewListener(localPriv, addr)
if err != nil {
return nil, nil, err
}
defer listener.Close()
netAddr := &lnwire.NetAddress{
IdentityKey: localPriv.PubKey(),
Address: listener.Addr().(*net.TCPAddr),
}
// Initiate a connection with a separate goroutine, and listen with our
// main one. If both errors are nil, then encryption+auth was succesful.
errChan := make(chan error)
connChan := make(chan net.Conn)
go func() {
conn, err := Dial(remotePriv, netAddr)
errChan <- err
connChan <- conn
}()
localConn, listenErr := listener.Accept()
if listenErr != nil {
return nil, nil, err
}
if dialErr := <-errChan; err != nil {
return nil, nil, dialErr
}
remoteConn := <-connChan
return localConn, remoteConn, nil
}
示例7: fetchChanFundingInfo
func fetchChanFundingInfo(nodeChanBucket *bolt.Bucket, channel *OpenChannel) error {
var b bytes.Buffer
if err := writeOutpoint(&b, channel.ChanID); err != nil {
return err
}
fundTxnKey := make([]byte, len(fundingTxnKey)+b.Len())
copy(fundTxnKey[:3], fundingTxnKey)
copy(fundTxnKey[3:], b.Bytes())
infoBytes := bytes.NewReader(nodeChanBucket.Get(fundTxnKey))
// TODO(roasbeef): can remove as channel ID *is* the funding point now.
channel.FundingOutpoint = &wire.OutPoint{}
if err := readOutpoint(infoBytes, channel.FundingOutpoint); err != nil {
return err
}
ourKeyBytes, err := wire.ReadVarBytes(infoBytes, 0, 34, "")
if err != nil {
return err
}
channel.OurMultiSigKey, err = btcec.ParsePubKey(ourKeyBytes, btcec.S256())
if err != nil {
return err
}
theirKeyBytes, err := wire.ReadVarBytes(infoBytes, 0, 34, "")
if err != nil {
return err
}
channel.TheirMultiSigKey, err = btcec.ParsePubKey(theirKeyBytes, btcec.S256())
if err != nil {
return err
}
channel.FundingWitnessScript, err = wire.ReadVarBytes(infoBytes, 0, 520, "")
if err != nil {
return err
}
scratch := make([]byte, 8)
if _, err := infoBytes.Read(scratch); err != nil {
return err
}
unixSecs := byteOrder.Uint64(scratch)
channel.CreationTime = time.Unix(int64(unixSecs), 0)
return nil
}
示例8: TestSigCacheAddEvictEntry
// TestSigCacheAddEvictEntry tests the eviction case where a new signature
// triplet is added to a full signature cache which should trigger randomized
// eviction, followed by adding the new element to the cache.
func TestSigCacheAddEvictEntry(t *testing.T) {
// Create a sigcache that can hold up to 100 entries.
sigCacheSize := uint(100)
sigCache := NewSigCache(sigCacheSize)
// Fill the sigcache up with some random sig triplets.
for i := uint(0); i < sigCacheSize; i++ {
msg, sig, key, err := genRandomSig()
if err != nil {
t.Fatalf("unable to generate random signature test data")
}
sigCache.Add(*msg, sig, key)
sigCopy, _ := btcec.ParseSignature(sig.Serialize(), btcec.S256())
keyCopy, _ := btcec.ParsePubKey(key.SerializeCompressed(), btcec.S256())
if !sigCache.Exists(*msg, sigCopy, keyCopy) {
t.Errorf("previously added item not found in signature" +
"cache")
}
}
// The sigcache should now have sigCacheSize entries within it.
if uint(len(sigCache.validSigs)) != sigCacheSize {
t.Fatalf("sigcache should now have %v entries, instead it has %v",
sigCacheSize, len(sigCache.validSigs))
}
// Add a new entry, this should cause eviction of a randomly chosen
// previous entry.
msgNew, sigNew, keyNew, err := genRandomSig()
if err != nil {
t.Fatalf("unable to generate random signature test data")
}
sigCache.Add(*msgNew, sigNew, keyNew)
// The sigcache should still have sigCache entries.
if uint(len(sigCache.validSigs)) != sigCacheSize {
t.Fatalf("sigcache should now have %v entries, instead it has %v",
sigCacheSize, len(sigCache.validSigs))
}
// The entry added above should be found within the sigcache.
sigNewCopy, _ := btcec.ParseSignature(sigNew.Serialize(), btcec.S256())
keyNewCopy, _ := btcec.ParsePubKey(keyNew.SerializeCompressed(), btcec.S256())
if !sigCache.Exists(*msgNew, sigNewCopy, keyNewCopy) {
t.Fatalf("previously added item not found in signature cache")
}
}
示例9: PrivKey
// PrivKey returns the private key for the address. It can fail if the address
// manager is watching-only or locked, or the address does not have any keys.
//
// This is part of the ManagedPubKeyAddress interface implementation.
func (a *managedAddress) PrivKey() (*btcec.PrivateKey, error) {
// No private keys are available for a watching-only address manager.
if a.manager.watchingOnly {
return nil, managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
a.manager.mtx.Lock()
defer a.manager.mtx.Unlock()
// Account manager must be unlocked to decrypt the private key.
if a.manager.locked {
return nil, managerError(ErrLocked, errLocked, nil)
}
// Decrypt the key as needed. Also, make sure it's a copy since the
// private key stored in memory can be cleared at any time. Otherwise
// the returned private key could be invalidated from under the caller.
privKeyCopy, err := a.unlock(a.manager.cryptoKeyPriv)
if err != nil {
return nil, err
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyCopy)
zero.Bytes(privKeyCopy)
return privKey, nil
}
示例10: Example_signMessage
// This example demonstrates signing a message with a secp256k1 private key that
// is first parsed form raw bytes and serializing the generated signature.
func Example_signMessage() {
// Decode a hex-encoded private key.
pkBytes, err := hex.DecodeString("22a47fa09a223f2aa079edf85a7c2d4f87" +
"20ee63e502ee2869afab7de234b80c")
if err != nil {
fmt.Println(err)
return
}
privKey, pubKey := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes)
// Sign a message using the private key.
message := "test message"
messageHash := chainhash.DoubleHashB([]byte(message))
signature, err := privKey.Sign(messageHash)
if err != nil {
fmt.Println(err)
return
}
// Serialize and display the signature.
fmt.Printf("Serialized Signature: %x\n", signature.Serialize())
// Verify the signature for the message using the public key.
verified := signature.Verify(messageHash, pubKey)
fmt.Printf("Signature Verified? %v\n", verified)
// Output:
// Serialized Signature: 304402201008e236fa8cd0f25df4482dddbb622e8a8b26ef0ba731719458de3ccd93805b022032f8ebe514ba5f672466eba334639282616bb3c2f0ab09998037513d1f9e3d6d
// Signature Verified? true
}
示例11: Example_decryptMessage
// This example demonstrates decrypting a message using a private key that is
// first parsed from raw bytes.
func Example_decryptMessage() {
// Decode the hex-encoded private key.
pkBytes, err := hex.DecodeString("a11b0a4e1a132305652ee7a8eb7848f6ad" +
"5ea381e3ce20a2c086a2e388230811")
if err != nil {
fmt.Println(err)
return
}
privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), pkBytes)
ciphertext, err := hex.DecodeString("35f644fbfb208bc71e57684c3c8b437402ca" +
"002047a2f1b38aa1a8f1d5121778378414f708fe13ebf7b4a7bb74407288c1958969" +
"00207cf4ac6057406e40f79961c973309a892732ae7a74ee96cd89823913b8b8d650" +
"a44166dc61ea1c419d47077b748a9c06b8d57af72deb2819d98a9d503efc59fc8307" +
"d14174f8b83354fac3ff56075162")
// Try decrypting the message.
plaintext, err := btcec.Decrypt(privKey, ciphertext)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(plaintext))
// Output:
// test message
}
示例12: updateCommitTx
// updateCommitTx signs, then sends an update to the remote peer adding a new
// commitment to their commitment chain which includes all the latest updates
// we've received+processed up to this point.
func (p *peer) updateCommitTx(state *commitmentState) (bool, error) {
sigTheirs, logIndexTheirs, err := state.channel.SignNextCommitment()
if err == lnwallet.ErrNoWindow {
peerLog.Tracef("revocation window exhausted, unable to send %v",
len(state.pendingBatch))
return false, nil
} else if err != nil {
return false, err
}
parsedSig, err := btcec.ParseSignature(sigTheirs, btcec.S256())
if err != nil {
return false, fmt.Errorf("unable to parse sig: %v", err)
}
commitSig := &lnwire.CommitSignature{
ChannelPoint: state.chanPoint,
CommitSig: parsedSig,
LogIndex: uint64(logIndexTheirs),
}
p.queueMsg(commitSig, nil)
// Move all pending updates to the map of cleared HTLC's, clearing out
// the set of pending updates.
for _, update := range state.pendingBatch {
// TODO(roasbeef): add parsed next-hop info to pending batch
// for multi-hop forwarding
state.clearedHTCLs[update.index] = update
}
state.logCommitTimer = nil
state.pendingBatch = nil
return true, nil
}
示例13: RecvActTwo
// RecvActTwo processes the second packet (act two) sent from the responder to
// the initiator. A succesful processing of this packet authenticates the
// initiator to the responder.
func (b *BrontideMachine) RecvActTwo(actTwo [ActTwoSize]byte) error {
var (
err error
e [33]byte
p [16]byte
)
copy(e[:], actTwo[:33])
copy(p[:], actTwo[33:])
// e
b.remoteEphemeral, err = btcec.ParsePubKey(e[:], btcec.S256())
if err != nil {
return err
}
b.mixHash(b.remoteEphemeral.SerializeCompressed())
// ee
s := btcec.GenerateSharedSecret(b.localEphemeral, b.remoteEphemeral)
b.mixKey(s)
if _, err := b.DecryptAndHash(p[:]); err != nil {
return err
}
return nil
}
示例14: Decode
// Decode fully populates the target ForwardingMessage from the raw bytes
// encoded within the io.Reader. In the case of any decoding errors, an error
// will be returned. If the method successs, then the new OnionPacket is
// ready to be processed by an instance of SphinxNode.
func (f *OnionPacket) Decode(r io.Reader) error {
var err error
f.Header = &MixHeader{}
var buf [1]byte
if _, err := io.ReadFull(r, buf[:]); err != nil {
return err
}
f.Header.Version = buf[0]
var ephemeral [33]byte
if _, err := io.ReadFull(r, ephemeral[:]); err != nil {
return err
}
f.Header.EphemeralKey, err = btcec.ParsePubKey(ephemeral[:], btcec.S256())
if err != nil {
return err
}
if _, err := io.ReadFull(r, f.Header.HeaderMAC[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, f.Header.RoutingInfo[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, f.Header.HopPayload[:]); err != nil {
return err
}
return nil
}
示例15: RecvActThree
// RecvActThree processes the final act (act three) sent from the initiator to
// the responder. After processing this act, the responder learns of the
// initiators's static public key. Decryption of the static key serves to
// authenticate the initiator to the responder.
func (b *BrontideMachine) RecvActThree(actThree [ActThreeSize]byte) error {
var (
err error
s [33 + 16]byte
p [16]byte
)
copy(s[:], actThree[:33+16])
copy(p[:], actThree[33+16:])
// s
remotePub, err := b.DecryptAndHash(s[:])
if err != nil {
return err
}
b.remoteStatic, err = btcec.ParsePubKey(remotePub, btcec.S256())
if err != nil {
return err
}
// se
se := btcec.GenerateSharedSecret(b.localEphemeral, b.remoteStatic)
b.mixKey(se)
if _, err := b.DecryptAndHash(p[:]); err != nil {
return err
}
// With the final ECDH operation complete, derive the session sending
// and receiving keys.
b.split()
return nil
}