From 4b6cd175615634bbb36c01dcd8f4bafdbb2a05e9 Mon Sep 17 00:00:00 2001 From: Dave Collins Date: Fri, 14 Nov 2014 12:07:39 -0600 Subject: [PATCH] Make RandomUint64 block until entropy is available. This commit modifies the RandomUint64 function so that rather than returning an io.ErrShortBuffer when the system does not have enough entropy available, it now blocks until it does have enough. This means that RandomUint64 will now always eventually succeed unless the entropy source is closed (which only really ever happens when the operating system is shutting down). The tests have also been updated for the change in semantics to maintain 100% coverage. Closes #23. --- common.go | 5 +---- common_test.go | 15 ++------------- 2 files changed, 3 insertions(+), 17 deletions(-) diff --git a/common.go b/common.go index dd6b61bd..792158ce 100644 --- a/common.go +++ b/common.go @@ -508,10 +508,7 @@ func writeVarBytes(w io.Writer, pver uint32, bytes []byte) error { // can be properly tested by passing a fake reader in the tests. func randomUint64(r io.Reader) (uint64, error) { var b [8]byte - n, err := r.Read(b[:]) - if n != len(b) { - return 0, io.ErrShortBuffer - } + _, err := io.ReadFull(r, b[:]) if err != nil { return 0, err } diff --git a/common_test.go b/common_test.go index 21706ee5..fbafe248 100644 --- a/common_test.go +++ b/common_test.go @@ -691,24 +691,13 @@ func TestRandomUint64(t *testing.T) { // and checks the results accordingly. func TestRandomUint64Errors(t *testing.T) { // Test short reads. - fr := &fakeRandReader{n: 2, err: nil} + fr := &fakeRandReader{n: 2, err: io.EOF} nonce, err := btcwire.TstRandomUint64(fr) - if err != io.ErrShortBuffer { + if err != io.ErrUnexpectedEOF { t.Errorf("TestRandomUint64Fails: Error not expected value of %v [%v]", io.ErrShortBuffer, err) } if nonce != 0 { t.Errorf("TestRandomUint64Fails: nonce is not 0 [%v]", nonce) } - - // Test err with full read. - fr = &fakeRandReader{n: 20, err: io.ErrClosedPipe} - nonce, err = btcwire.TstRandomUint64(fr) - if err != io.ErrClosedPipe { - t.Errorf("TestRandomUint64Fails: Error not expected value of %v [%v]", - io.ErrClosedPipe, err) - } - if nonce != 0 { - t.Errorf("TestRandomUint64Fails: nonce is not 0 [%v]", nonce) - } }