From e0fd32858970fb24a293452aec37d9161444a1b6 Mon Sep 17 00:00:00 2001 From: Ethan Buchman <ethan@coinculture.info> Date: Thu, 25 Feb 2016 03:50:33 +0000 Subject: [PATCH] godeps --- Godeps/Godeps.json | 24 +- .../src/github.com/eris-ltd/common/LICENSE | 21 + .../eris-ltd/common/go/ipfs/LICENSE.md | 201 ++++++ .../eris-ltd/common/go/log/logger_new.go | 112 +++ .../eris-ltd/common/go/log/logger_old.go | 244 +++++++ .../github.com/eris-ltd/mint-client/LICENSE | 675 ++++++++++++++++++ .../eris-ltd/mint-client/mintx/core/core.go | 643 +++++++++++++++++ .../eris-ltd/mint-client/mintx/core/log.go | 11 + .../mattn/go-colorable/colorable_windows.go | 2 +- .../src/github.com/mattn/go-isatty/README.md | 37 + .../src/github.com/mattn/go-isatty/doc.go | 2 + .../github.com/mattn/go-isatty/isatty_bsd.go | 17 + .../mattn/go-isatty/isatty_linux.go | 17 + .../mattn/go-isatty/isatty_windows.go | 18 + .../stretchr/testify/require/doc.go | 77 -- .../testify/require/forward_requirements.go | 211 ------ .../require/forward_requirements_test.go | 260 ------- .../stretchr/testify/require/requirements.go | 271 ------- .../testify/require/requirements_test.go | 266 ------- .../github.com/stretchr/testify/suite/doc.go | 65 -- .../stretchr/testify/suite/interfaces.go | 34 - .../stretchr/testify/suite/suite.go | 114 --- .../stretchr/testify/suite/suite_test.go | 208 ------ .../src/github.com/tendermint/go-rpc/LICENSE | 201 ++++++ .../github.com/tendermint/go-rpc/README.md | 4 + .../tendermint/go-rpc/client/http_client.go | 169 +++++ .../tendermint/go-rpc/client/log.go | 7 + .../tendermint/go-rpc/client/ws_client.go | 129 ++++ .../tendermint/go-rpc/server/handlers.go | 563 +++++++++++++++ .../tendermint/go-rpc/server/http_params.go | 89 +++ .../tendermint/go-rpc/server/http_server.go | 123 ++++ .../tendermint/go-rpc/server/log.go | 7 + .../tendermint/go-rpc/types/types.go | 91 +++ .../github.com/tendermint/go-rpc/version.go | 7 + .../tendermint/tendermint/mempool/reactor.go | 7 +- erisdb/serve.go | 2 +- 36 files changed, 3409 insertions(+), 1520 deletions(-) create mode 100644 Godeps/_workspace/src/github.com/eris-ltd/common/LICENSE create mode 100644 Godeps/_workspace/src/github.com/eris-ltd/common/go/ipfs/LICENSE.md create mode 100644 Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_new.go create mode 100644 Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_old.go create mode 100644 Godeps/_workspace/src/github.com/eris-ltd/mint-client/LICENSE create mode 100644 Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/core.go create mode 100644 Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/log.go create mode 100644 Godeps/_workspace/src/github.com/mattn/go-isatty/README.md create mode 100644 Godeps/_workspace/src/github.com/mattn/go-isatty/doc.go create mode 100644 Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_bsd.go create mode 100644 Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_linux.go create mode 100644 Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_windows.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/require/doc.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/require/requirements.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/suite/doc.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/suite/interfaces.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/suite/suite.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/suite/suite_test.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/LICENSE create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/README.md create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/client/http_client.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/client/log.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/client/ws_client.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/server/handlers.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_params.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_server.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/server/log.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/types/types.go create mode 100644 Godeps/_workspace/src/github.com/tendermint/go-rpc/version.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index c1596e21..5be182f9 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -2,7 +2,7 @@ "ImportPath": "github.com/eris-ltd/eris-db", "GoVersion": "go1.5.1", "Packages": [ - "./..." + "./erisdb/" ], "Deps": [ { @@ -19,6 +19,14 @@ "ImportPath": "github.com/agl/ed25519/edwards25519", "Rev": "d2b94fd789ea21d12fac1a4443dd3a3f79cda72c" }, + { + "ImportPath": "github.com/eris-ltd/common/go/log", + "Rev": "26df169480eef97df7ed9f5419b7367895d077b4" + }, + { + "ImportPath": "github.com/eris-ltd/mint-client/mintx/core", + "Rev": "5f320d2908e20efce7a56f28493be8b04d4f85ef" + }, { "ImportPath": "github.com/gin-gonic/gin", "Comment": "v1.0rc1-104-g1a7ab6e", @@ -46,6 +54,10 @@ "ImportPath": "github.com/mattn/go-colorable", "Rev": "043ae16291351db8465272edf465c9f388161627" }, + { + "ImportPath": "github.com/mattn/go-isatty", + "Rev": "fdbe02a1b44e75977b2690062b83cf507d70c013" + }, { "ImportPath": "github.com/naoina/go-stringutil", "Rev": "360db0db4b01d34e12a2ec042c09e7d37fece761" @@ -63,16 +75,6 @@ "Comment": "v1.0-17-g089c718", "Rev": "089c7181b8c728499929ff09b62d3fdd8df8adff" }, - { - "ImportPath": "github.com/stretchr/testify/require", - "Comment": "v1.0-17-g089c718", - "Rev": "089c7181b8c728499929ff09b62d3fdd8df8adff" - }, - { - "ImportPath": "github.com/stretchr/testify/suite", - "Comment": "v1.0-17-g089c718", - "Rev": "089c7181b8c728499929ff09b62d3fdd8df8adff" - }, { "ImportPath": "github.com/syndtr/goleveldb/leveldb", "Rev": "63c9e642efad852f49e20a6f90194cae112fd2ac" diff --git a/Godeps/_workspace/src/github.com/eris-ltd/common/LICENSE b/Godeps/_workspace/src/github.com/eris-ltd/common/LICENSE new file mode 100644 index 00000000..3723afa1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/eris-ltd/common/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Eris Industries, Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/eris-ltd/common/go/ipfs/LICENSE.md b/Godeps/_workspace/src/github.com/eris-ltd/common/go/ipfs/LICENSE.md new file mode 100644 index 00000000..8dada3ed --- /dev/null +++ b/Godeps/_workspace/src/github.com/eris-ltd/common/go/ipfs/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_new.go b/Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_new.go new file mode 100644 index 00000000..4da859fa --- /dev/null +++ b/Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_new.go @@ -0,0 +1,112 @@ +package log + +import ( + "fmt" + "os/exec" + "runtime" + "sort" + + log "github.com/Sirupsen/logrus" +) + +type ErisFormatter struct{} + +const ( + arrowTag = "=>" + + // Where to place `tag=comment` on screen. + offset = 44 + + // Space between a log message and a tag name + spacing = 4 +) + +var ( + // See terminfo(5) for the list of commands. + escReset = tput("sgr0") + escBold = tput("bold") + // http://worldwidemann.com/content/images/2015/03/finalterm-colors.png + escTag = tput("setaf", 241) +) + +// Tput asks the terminfo database for a particular escape sequence. +func tput(command string, params ...interface{}) []byte { + args := []string{command} + + // Don't do anything on Windows. + if runtime.GOOS == "windows" { + return []byte{} + } + + for _, param := range params { + switch param.(type) { + case string: + args = append(args, param.(string)) + case int: + args = append(args, fmt.Sprintf("%d", param)) + } + } + + out, err := exec.Command("tput", args...).Output() + if err != nil { + return []byte{} + } + + return out +} + +// highlight emphasizes a tag and a comment. It returns the highlighted +// text along with an offset where to place it on screen. +func highlight(tag, comment string) (adjustedOffset int, text string) { + tagDecorated := fmt.Sprintf("%s%s%s", escTag, tag, escReset) + commentDecorated := fmt.Sprintf("%s%s%s", escBold, comment, escReset) + + if tag == arrowTag { + return offset + 2, fmt.Sprintf("%s", commentDecorated) + } else { + return offset - len(tag) + 1, fmt.Sprintf("%s=%s", tagDecorated, commentDecorated) + } +} + +// Format implements the logrus.Formatter interface. It returns a formatted +// log line as a slice of bytes. +func (f ErisFormatter) Format(entry *log.Entry) (out []byte, err error) { + // Sort tag names in alphabetical order. + var keys []string + for key, _ := range entry.Data { + keys = append(keys, key) + } + sort.Strings(keys) + + // Display a message and the first tag. + if len(entry.Data) > 0 { + tag, comment := keys[0], fmt.Sprintf("%v", entry.Data[keys[0]]) + + // Highlight the tag. + adjustedOffset, text := highlight(tag, comment) + + if len(entry.Message) < adjustedOffset-spacing { + // Message with the tag inline. + out = append(out, fmt.Sprintf("%-*s%s\n", adjustedOffset, entry.Message, text)...) + } else { + // Message with the tag on a separate line. + out = append(out, fmt.Sprintf("%s\n%-*s%s\n", entry.Message, adjustedOffset, "", text)...) + } + + // Remove the used tag name. + keys = keys[1:] + } else { + // Message without tags. + out = append(out, fmt.Sprintln(entry.Message)...) + } + + // Display every other tag on a separate line. + for _, key := range keys { + // Highlight the tag. + adjustedOffset, text := highlight(key, fmt.Sprintf("%v", entry.Data[key])) + + out = append(out, fmt.Sprintf("%-*s%s\n", adjustedOffset, "", text)...) + } + + return out, nil +} diff --git a/Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_old.go b/Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_old.go new file mode 100644 index 00000000..193e1475 --- /dev/null +++ b/Godeps/_workspace/src/github.com/eris-ltd/common/go/log/logger_old.go @@ -0,0 +1,244 @@ +package log + +//XXX this pkg is being deprecated in favour of logrus + +import ( + "fmt" + "io" + "os" + "sync" + "sync/atomic" +) + +type LogLevel uint8 + +const ( + LogLevelError LogLevel = iota + LogLevelWarn + LogLevelInfo + LogLevelDebug +) + +const ( + Version = "0.1.1" // atomic running +) + +//-------------------------------------------------------------------------------- +// thread safe logger that fires messages from multiple packages one at a time + +func init() { + go readLoop() +} + +var ( + // control access to loggers + mtx sync.Mutex + loggers = make(map[string]*Logger) + + // access to writers managed by channels + writer io.Writer = os.Stdout + errWriter io.Writer = os.Stderr + + chanBuffer = 100 + writeCh = make(chan []byte, chanBuffer) + errorCh = make(chan []byte, chanBuffer) + + quitCh = make(chan struct{}) + + running uint32 // atomic +) + +type Logger struct { + Level LogLevel + Pkg string + + // these are here for easy access + // for functions that want the writer + Writer *SafeWriter + ErrWriter *SafeWriter +} + +// add a default logger with pkg name +func AddLogger(pkg string) *Logger { + l := &Logger{ + Level: LogLevelError, + Pkg: pkg, + Writer: NewSafeWriter(writeCh), + ErrWriter: NewSafeWriter(errorCh), + } + mtx.Lock() + loggers[pkg] = l + mtx.Unlock() + return l +} + +func SetLogLevelGlobal(level LogLevel) { + mtx.Lock() + defer mtx.Unlock() + + for _, l := range loggers { + l.Level = level + } +} + +// set levels for individual packages +func SetLogLevel(pkg string, level LogLevel) { + mtx.Lock() + defer mtx.Unlock() + + if l, ok := loggers[pkg]; ok { + l.Level = level + if level > LogLevelInfo { + // TODO: wrap the writers to print [<pkg>] + } + } +} + +// set level and writer for all loggers +func SetLoggers(level LogLevel, w io.Writer, ew io.Writer) { + mtx.Lock() + defer mtx.Unlock() + for _, l := range loggers { + l.Level = level + if l.Level > LogLevelInfo { + // TODO: wrap the writers to print [<pkg>] + } + } + writer = w + errWriter = ew +} + +//-------------------------------------------------------------------------------- +// concurrency + +func readLoop() { + if atomic.CompareAndSwapUint32(&running, 0, 1) { + LOOP: + for { + select { + case b := <-writeCh: + writer.Write(b) + case b := <-errorCh: + errWriter.Write(b) + case <-quitCh: + break LOOP + + } + } + } +} + +func flush(ch chan []byte, w io.Writer) { + for { + select { + case b := <-ch: + w.Write(b) + default: + return + } + } +} + +// Flush the log channels. Concurrent users of the logger should quit before +// Flush() is called to ensure it completes. +func Flush() { + if atomic.CompareAndSwapUint32(&running, 1, 0) { + flush(writeCh, writer) + flush(errorCh, errWriter) + quitCh <- struct{}{} + } +} + +//-------------------------------------------------------------------------------- +// a SafeWriter implements Writer and fires its bytes over the channel +// to be written to the writer or errWriter + +type SafeWriter struct { + ch chan []byte +} + +func NewSafeWriter(ch chan []byte) *SafeWriter { + return &SafeWriter{ch} +} + +func (sw *SafeWriter) Write(b []byte) (int, error) { + sw.ch <- b + return len(b), nil +} + +// thread safe writes +func writef(s string, args ...interface{}) { + writeCh <- []byte(fmt.Sprintf(s, args...)) +} + +func writeln(s ...interface{}) { + writeCh <- []byte(fmt.Sprintln(s...)) +} + +func errorf(s string, args ...interface{}) { + errorCh <- []byte(fmt.Sprintf(s, args...)) +} + +func errorln(s ...interface{}) { + errorCh <- []byte(fmt.Sprintln(s...)) +} + +//-------------------------------------------------------------------------------- +// public logger functions + +// Printf and Println write to the Writer no matter what +func (l *Logger) Printf(s string, args ...interface{}) { + writef(s, args...) +} + +func (l *Logger) Println(s ...interface{}) { + writeln(s...) +} + +// Errorf and Errorln write to the ErrWriter no matter what +func (l *Logger) Errorf(s string, args ...interface{}) { + errorf(s, args...) +} + +func (l *Logger) Errorln(s ...interface{}) { + errorln(s...) +} + +// Warnf and Warnln write to the Writer if log level >= 1 +func (l *Logger) Warnf(s string, args ...interface{}) { + if l.Level > LogLevelError { + writef(s, args...) + } +} + +func (l *Logger) Warnln(s ...interface{}) { + if l.Level > LogLevelError { + writeln(s...) + } +} + +// Infof and Infoln write to the Writer if log level >= 2 +func (l *Logger) Infof(s string, args ...interface{}) { + if l.Level > LogLevelWarn { + writef(s, args...) + } +} + +func (l *Logger) Infoln(s ...interface{}) { + if l.Level > LogLevelWarn { + writeln(s...) + } +} + +// Debugf and Debugln write to the Writer if log level >= 3 +func (l *Logger) Debugf(s string, args ...interface{}) { + if l.Level > LogLevelInfo { + writef(s, args...) + } +} + +func (l *Logger) Debugln(s ...interface{}) { + if l.Level > LogLevelInfo { + writeln(s...) + } +} diff --git a/Godeps/_workspace/src/github.com/eris-ltd/mint-client/LICENSE b/Godeps/_workspace/src/github.com/eris-ltd/mint-client/LICENSE new file mode 100644 index 00000000..733c0723 --- /dev/null +++ b/Godeps/_workspace/src/github.com/eris-ltd/mint-client/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. + diff --git a/Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/core.go b/Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/core.go new file mode 100644 index 00000000..31622dad --- /dev/null +++ b/Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/core.go @@ -0,0 +1,643 @@ +package core + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "strconv" + "strings" + "time" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" + ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" + rtypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" + cclient "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" +) + +var ( + MaxCommitWaitTimeSeconds = 10 +) + +//------------------------------------------------------------------------------------ +// core functions with string args. +// validates strings and forms transaction + +func Send(nodeAddr, signAddr, pubkey, addr, toAddr, amtS, nonceS string) (*types.SendTx, error) { + pub, amt, nonce, err := checkCommon(nodeAddr, signAddr, pubkey, addr, amtS, nonceS) + if err != nil { + return nil, err + } + + if toAddr == "" { + return nil, fmt.Errorf("destination address must be given with --to flag") + } + + toAddrBytes, err := hex.DecodeString(toAddr) + if err != nil { + return nil, fmt.Errorf("toAddr is bad hex: %v", err) + } + + tx := types.NewSendTx() + tx.AddInputWithNonce(pub, amt, int(nonce)) + tx.AddOutput(toAddrBytes, amt) + + return tx, nil +} + +func Call(nodeAddr, signAddr, pubkey, addr, toAddr, amtS, nonceS, gasS, feeS, data string) (*types.CallTx, error) { + pub, amt, nonce, err := checkCommon(nodeAddr, signAddr, pubkey, addr, amtS, nonceS) + if err != nil { + return nil, err + } + + toAddrBytes, err := hex.DecodeString(toAddr) + if err != nil { + return nil, fmt.Errorf("toAddr is bad hex: %v", err) + } + + fee, err := strconv.ParseInt(feeS, 10, 64) + if err != nil { + return nil, fmt.Errorf("fee is misformatted: %v", err) + } + + gas, err := strconv.ParseInt(gasS, 10, 64) + if err != nil { + return nil, fmt.Errorf("gas is misformatted: %v", err) + } + + dataBytes, err := hex.DecodeString(data) + if err != nil { + return nil, fmt.Errorf("data is bad hex: %v", err) + } + + tx := types.NewCallTxWithNonce(pub, toAddrBytes, dataBytes, amt, gas, fee, int(nonce)) + return tx, nil +} + +func Name(nodeAddr, signAddr, pubkey, addr, amtS, nonceS, feeS, name, data string) (*types.NameTx, error) { + pub, amt, nonce, err := checkCommon(nodeAddr, signAddr, pubkey, addr, amtS, nonceS) + if err != nil { + return nil, err + } + + fee, err := strconv.ParseInt(feeS, 10, 64) + if err != nil { + return nil, fmt.Errorf("fee is misformatted: %v", err) + } + + tx := types.NewNameTxWithNonce(pub, name, data, amt, fee, int(nonce)) + return tx, nil +} + +type PermFunc struct { + Name string + Args string +} + +var PermsFuncs = []PermFunc{ + PermFunc{"set_base", "address, permission flag, value"}, + PermFunc{"unset_base", "address, permission flag"}, + PermFunc{"set_global", "permission flag, value"}, + PermFunc{"add_role", "address, role"}, + PermFunc{"rm_role", "address, role"}, +} + +func Permissions(nodeAddr, signAddr, pubkey, addrS, nonceS, permFunc string, argsS []string) (*types.PermissionsTx, error) { + pub, _, nonce, err := checkCommon(nodeAddr, signAddr, pubkey, addrS, "0", nonceS) + if err != nil { + return nil, err + } + var args ptypes.PermArgs + switch permFunc { + case "set_base": + addr, pF, err := decodeAddressPermFlag(argsS[0], argsS[1]) + if err != nil { + return nil, err + } + if len(argsS) != 3 { + return nil, fmt.Errorf("set_base also takes a value (true or false)") + } + var value bool + if argsS[2] == "true" { + value = true + } else if argsS[2] == "false" { + value = false + } else { + return nil, fmt.Errorf("Unknown value %s", argsS[2]) + } + args = &ptypes.SetBaseArgs{addr, pF, value} + case "unset_base": + addr, pF, err := decodeAddressPermFlag(argsS[0], argsS[1]) + if err != nil { + return nil, err + } + args = &ptypes.UnsetBaseArgs{addr, pF} + case "set_global": + pF, err := ptypes.PermStringToFlag(argsS[0]) + if err != nil { + return nil, err + } + var value bool + if argsS[1] == "true" { + value = true + } else if argsS[1] == "false" { + value = false + } else { + return nil, fmt.Errorf("Unknown value %s", argsS[1]) + } + args = &ptypes.SetGlobalArgs{pF, value} + case "add_role": + addr, err := hex.DecodeString(argsS[0]) + if err != nil { + return nil, err + } + args = &ptypes.AddRoleArgs{addr, argsS[1]} + case "rm_role": + addr, err := hex.DecodeString(argsS[0]) + if err != nil { + return nil, err + } + args = &ptypes.RmRoleArgs{addr, argsS[1]} + default: + return nil, fmt.Errorf("Invalid permission function for use in PermissionsTx: %s", permFunc) + } + // args := snativeArgs( + tx := types.NewPermissionsTxWithNonce(pub, args, int(nonce)) + return tx, nil +} + +func decodeAddressPermFlag(addrS, permFlagS string) (addr []byte, pFlag ptypes.PermFlag, err error) { + if addr, err = hex.DecodeString(addrS); err != nil { + return + } + if pFlag, err = ptypes.PermStringToFlag(permFlagS); err != nil { + return + } + return +} + +type NameGetter struct { + client cclient.Client +} + +func (n NameGetter) GetNameRegEntry(name string) *types.NameRegEntry { + entry, err := n.client.GetName(name) + if err != nil { + panic(err) + } + return entry.Entry +} + +/* +func coreNewAccount(nodeAddr, pubkey, chainID string) (*types.NewAccountTx, error) { + pub, _, _, err := checkCommon(nodeAddr, pubkey, "", "0", "0") + if err != nil { + return nil, err + } + + client := cclient.NewClient(nodeAddr, "HTTP") + return types.NewNewAccountTx(NameGetter{client}, pub, chainID) +} +*/ + +func Bond(nodeAddr, signAddr, pubkey, unbondAddr, amtS, nonceS string) (*types.BondTx, error) { + pub, amt, nonce, err := checkCommon(nodeAddr, signAddr, pubkey, "", amtS, nonceS) + if err != nil { + return nil, err + } + var pubKey account.PubKeyEd25519 + var unbondAddrBytes []byte + + if unbondAddr == "" { + pkb, _ := hex.DecodeString(pubkey) + copy(pubKey[:], pkb) + unbondAddrBytes = pubKey.Address() + } else { + unbondAddrBytes, err = hex.DecodeString(unbondAddr) + if err != nil { + return nil, fmt.Errorf("unbondAddr is bad hex: %v", err) + } + + } + + tx, err := types.NewBondTx(pub) + if err != nil { + return nil, err + } + tx.AddInputWithNonce(pub, amt, int(nonce)) + tx.AddOutput(unbondAddrBytes, amt) + + return tx, nil +} + +func Unbond(addrS, heightS string) (*types.UnbondTx, error) { + if addrS == "" { + return nil, fmt.Errorf("Validator address must be given with --addr flag") + } + + addrBytes, err := hex.DecodeString(addrS) + if err != nil { + return nil, fmt.Errorf("addr is bad hex: %v", err) + } + + height, err := strconv.ParseInt(heightS, 10, 32) + if err != nil { + return nil, fmt.Errorf("height is misformatted: %v", err) + } + + return &types.UnbondTx{ + Address: addrBytes, + Height: int(height), + }, nil +} + +func Rebond(addrS, heightS string) (*types.RebondTx, error) { + if addrS == "" { + return nil, fmt.Errorf("Validator address must be given with --addr flag") + } + + addrBytes, err := hex.DecodeString(addrS) + if err != nil { + return nil, fmt.Errorf("addr is bad hex: %v", err) + } + + height, err := strconv.ParseInt(heightS, 10, 32) + if err != nil { + return nil, fmt.Errorf("height is misformatted: %v", err) + } + + return &types.RebondTx{ + Address: addrBytes, + Height: int(height), + }, nil +} + +//------------------------------------------------------------------------------------ +// sign and broadcast + +func Pub(addr, rpcAddr string) (pubBytes []byte, err error) { + args := map[string]string{ + "addr": addr, + } + pubS, err := RequestResponse(rpcAddr, "pub", args) + if err != nil { + return + } + return hex.DecodeString(pubS) +} + +func Sign(signBytes, signAddr, signRPC string) (sig [64]byte, err error) { + args := map[string]string{ + "msg": signBytes, + "hash": signBytes, // backwards compatibility + "addr": signAddr, + } + sigS, err := RequestResponse(signRPC, "sign", args) + if err != nil { + return + } + sigBytes, err := hex.DecodeString(sigS) + if err != nil { + return + } + copy(sig[:], sigBytes) + return +} + +func Broadcast(tx types.Tx, broadcastRPC string) (*rtypes.Receipt, error) { + client := cclient.NewClient(broadcastRPC, "JSONRPC") + rec, err := client.BroadcastTx(tx) + if err != nil { + return nil, err + } + return &rec.Receipt, nil +} + +//------------------------------------------------------------------------------------ +// utils for talking to the key server + +type HTTPResponse struct { + Response string + Error string +} + +func RequestResponse(addr, method string, args map[string]string) (string, error) { + b, err := json.Marshal(args) + if err != nil { + return "", err + } + endpoint := fmt.Sprintf("%s/%s", addr, method) + logger.Debugf("Sending request body (%s): %s\n", endpoint, string(b)) + req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(b)) + if err != nil { + return "", err + } + req.Header.Add("Content-Type", "application/json") + res, errS, err := requestResponse(req) + if err != nil { + return "", fmt.Errorf("Error calling eris-keys at %s: %s", endpoint, err.Error()) + } + if errS != "" { + return "", fmt.Errorf("Error (string) calling eris-keys at %s: %s", endpoint, errS) + } + return res, nil +} + +func requestResponse(req *http.Request) (string, string, error) { + client := new(http.Client) + resp, err := client.Do(req) + if err != nil { + return "", "", err + } + if resp.StatusCode >= 400 { + return "", "", fmt.Errorf(resp.Status) + } + return unpackResponse(resp) +} + +func unpackResponse(resp *http.Response) (string, string, error) { + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + return "", "", err + } + r := new(HTTPResponse) + if err := json.Unmarshal(b, r); err != nil { + return "", "", err + } + return r.Response, r.Error, nil +} + +//------------------------------------------------------------------------------------ +// sign and broadcast convenience + +// tx has either one input or we default to the first one (ie for send/bond) +// TODO: better support for multisig and bonding +func signTx(signAddr, chainID string, tx_ types.Tx) ([]byte, types.Tx, error) { + signBytes := fmt.Sprintf("%X", account.SignBytes(chainID, tx_)) + var inputAddr []byte + var sigED account.SignatureEd25519 + switch tx := tx_.(type) { + case *types.SendTx: + inputAddr = tx.Inputs[0].Address + defer func(s *account.SignatureEd25519) { tx.Inputs[0].Signature = *s }(&sigED) + case *types.NameTx: + inputAddr = tx.Input.Address + defer func(s *account.SignatureEd25519) { tx.Input.Signature = *s }(&sigED) + case *types.CallTx: + inputAddr = tx.Input.Address + defer func(s *account.SignatureEd25519) { tx.Input.Signature = *s }(&sigED) + case *types.PermissionsTx: + inputAddr = tx.Input.Address + defer func(s *account.SignatureEd25519) { tx.Input.Signature = *s }(&sigED) + case *types.BondTx: + inputAddr = tx.Inputs[0].Address + defer func(s *account.SignatureEd25519) { + tx.Signature = *s + tx.Inputs[0].Signature = *s + }(&sigED) + case *types.UnbondTx: + inputAddr = tx.Address + defer func(s *account.SignatureEd25519) { tx.Signature = *s }(&sigED) + case *types.RebondTx: + inputAddr = tx.Address + defer func(s *account.SignatureEd25519) { tx.Signature = *s }(&sigED) + } + addrHex := fmt.Sprintf("%X", inputAddr) + sig, err := Sign(signBytes, addrHex, signAddr) + if err != nil { + return nil, nil, err + } + sigED = account.SignatureEd25519(sig) + logger.Debugf("SIG: %X\n", sig) + return inputAddr, tx_, nil +} + +type TxResult struct { + BlockHash []byte // all txs get in a block + Hash []byte // all txs get a hash + + // only CallTx + Address []byte // only for new contracts + Return []byte + Exception string + + //TODO: make Broadcast() errors more responsive so we + // can differentiate mempool errors from other +} + +func SignAndBroadcast(chainID, nodeAddr, signAddr string, tx types.Tx, sign, broadcast, wait bool) (txResult *TxResult, err error) { + var inputAddr []byte + if sign { + inputAddr, tx, err = signTx(signAddr, chainID, tx) + if err != nil { + return nil, err + } + } + + if broadcast { + if wait { + var ch chan Msg + ch, err = subscribeAndWait(tx, chainID, nodeAddr, inputAddr) + if err != nil { + return nil, err + } else { + defer func() { + if err != nil { + // if broadcast threw an error, just return + return + } + logger.Debugln("Waiting for tx to be committed ...") + msg := <-ch + if msg.Error != nil { + logger.Infof("Encountered error waiting for event: %v\n", msg.Error) + err = msg.Error + } else { + txResult.BlockHash = msg.BlockHash + txResult.Return = msg.Value + txResult.Exception = msg.Exception + } + }() + } + } + var receipt *rtypes.Receipt + receipt, err = Broadcast(tx, nodeAddr) + if err != nil { + return nil, err + } + txResult = &TxResult{ + Hash: receipt.TxHash, + } + if tx_, ok := tx.(*types.CallTx); ok { + if len(tx_.Address) == 0 { + txResult.Address = types.NewContractAddress(tx_.Input.Address, tx_.Input.Sequence) + } + } + } + return +} + +//------------------------------------------------------------------------------------ +// wait for events + +type Msg struct { + BlockHash []byte + Value []byte + Exception string + Error error +} + +func subscribeAndWait(tx types.Tx, chainID, nodeAddr string, inputAddr []byte) (chan Msg, error) { + // subscribe to event and wait for tx to be committed + wsAddr := strings.TrimPrefix(nodeAddr, "http://") + wsAddr = "ws://" + wsAddr + "websocket" + logger.Debugf("Websocket Address %s\n", wsAddr) + wsClient := cclient.NewWSClient(wsAddr) + wsClient.Start() + eid := types.EventStringAccInput(inputAddr) + if err := wsClient.Subscribe(eid); err != nil { + return nil, fmt.Errorf("Error subscribing to AccInput event: %v", err) + } + if err := wsClient.Subscribe(types.EventStringNewBlock()); err != nil { + return nil, fmt.Errorf("Error subscribing to NewBlock event: %v", err) + } + + resultChan := make(chan Msg, 1) + + var latestBlockHash []byte + + // Read message + go func() { + for { + result := <-wsClient.EventsCh + // if its a block, remember the block hash + blockData, ok := result.Data.(types.EventDataNewBlock) + if ok { + logger.Infoln(blockData.Block) + latestBlockHash = blockData.Block.Hash() + continue + } + + // we don't accept events unless they came after a new block (ie. in) + if latestBlockHash == nil { + continue + } + + if result.Event != eid { + logger.Debugf("received unsolicited event! Got %s, expected %s\n", result.Event, eid) + continue + } + + data, ok := result.Data.(types.EventDataTx) + if !ok { + resultChan <- Msg{Error: fmt.Errorf("response error: expected result.Data to be *types.EventDataTx")} + return + } + + if !bytes.Equal(types.TxID(chainID, data.Tx), types.TxID(chainID, tx)) { + logger.Debugf("Received event for same input from another transaction: %X\n", types.TxID(chainID, data.Tx)) + continue + } + + if data.Exception != "" { + resultChan <- Msg{BlockHash: latestBlockHash, Value: data.Return, Exception: data.Exception} + return + } + + // GOOD! + resultChan <- Msg{BlockHash: latestBlockHash, Value: data.Return} + return + } + }() + + // txs should take no more than 10 seconds + timeoutTicker := time.Tick(time.Duration(MaxCommitWaitTimeSeconds) * time.Second) + + go func() { + <-timeoutTicker + resultChan <- Msg{Error: fmt.Errorf("timed out waiting for event")} + return + }() + return resultChan, nil +} + +//------------------------------------------------------------------------------------ +// convenience function + +func checkCommon(nodeAddr, signAddr, pubkey, addr, amtS, nonceS string) (pub account.PubKey, amt int64, nonce int64, err error) { + if amtS == "" { + err = fmt.Errorf("input must specify an amount with the --amt flag") + return + } + + var pubKeyBytes []byte + if pubkey == "" && addr == "" { + err = fmt.Errorf("at least one of --pubkey or --addr must be given") + return + } else if pubkey != "" { + if addr != "" { + // NOTE: if --addr given byt MINTX_PUBKEY is set, the pubkey still wins + // TODO: fix this + logger.Errorln("you have specified both a pubkey and an address. the pubkey takes precedent") + } + pubKeyBytes, err = hex.DecodeString(pubkey) + if err != nil { + err = fmt.Errorf("pubkey is bad hex: %v", err) + return + } + } else { + // grab the pubkey from eris-keys + pubKeyBytes, err = Pub(addr, signAddr) + if err != nil { + err = fmt.Errorf("failed to fetch pubkey for address (%s): %v", addr, err) + return + } + + } + + if len(pubKeyBytes) == 0 { + err = fmt.Errorf("Error resolving public key") + return + } + + amt, err = strconv.ParseInt(amtS, 10, 64) + if err != nil { + err = fmt.Errorf("amt is misformatted: %v", err) + } + + var pubArray [32]byte + copy(pubArray[:], pubKeyBytes) + pub = account.PubKeyEd25519(pubArray) + addrBytes := pub.Address() + + if nonceS == "" { + if nodeAddr == "" { + err = fmt.Errorf("input must specify a nonce with the --nonce flag or use --node-addr (or MINTX_NODE_ADDR) to fetch the nonce from a node") + return + } + + // fetch nonce from node + client := cclient.NewClient(nodeAddr, "HTTP") + ac, err2 := client.GetAccount(addrBytes) + if err2 != nil { + err = fmt.Errorf("Error connecting to node (%s) to fetch nonce: %s", nodeAddr, err2.Error()) + return + } + if ac == nil || ac.Account == nil { + err = fmt.Errorf("unknown account %X", addrBytes) + return + } + nonce = int64(ac.Account.Sequence) + 1 + } else { + nonce, err = strconv.ParseInt(nonceS, 10, 64) + if err != nil { + err = fmt.Errorf("nonce is misformatted: %v", err) + return + } + } + + return +} diff --git a/Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/log.go b/Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/log.go new file mode 100644 index 00000000..e8fbb126 --- /dev/null +++ b/Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core/log.go @@ -0,0 +1,11 @@ +package core + +import ( + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/eris-ltd/common/go/log" +) + +var logger *Logger + +func init() { + logger = AddLogger("mintx-core") +} diff --git a/Godeps/_workspace/src/github.com/mattn/go-colorable/colorable_windows.go b/Godeps/_workspace/src/github.com/mattn/go-colorable/colorable_windows.go index 6a278780..a6c91aeb 100644 --- a/Godeps/_workspace/src/github.com/mattn/go-colorable/colorable_windows.go +++ b/Godeps/_workspace/src/github.com/mattn/go-colorable/colorable_windows.go @@ -10,7 +10,7 @@ import ( "syscall" "unsafe" - "github.com/mattn/go-isatty" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/mattn/go-isatty" ) const ( diff --git a/Godeps/_workspace/src/github.com/mattn/go-isatty/README.md b/Godeps/_workspace/src/github.com/mattn/go-isatty/README.md new file mode 100644 index 00000000..74845de4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/mattn/go-isatty/README.md @@ -0,0 +1,37 @@ +# go-isatty + +isatty for golang + +## Usage + +```go +package main + +import ( + "fmt" + "github.com/mattn/go-isatty" + "os" +) + +func main() { + if isatty.IsTerminal(os.Stdout.Fd()) { + fmt.Println("Is Terminal") + } else { + fmt.Println("Is Not Terminal") + } +} +``` + +## Installation + +``` +$ go get github.com/mattn/go-isatty +``` + +# License + +MIT + +# Author + +Yasuhiro Matsumoto (a.k.a mattn) diff --git a/Godeps/_workspace/src/github.com/mattn/go-isatty/doc.go b/Godeps/_workspace/src/github.com/mattn/go-isatty/doc.go new file mode 100644 index 00000000..17d4f90e --- /dev/null +++ b/Godeps/_workspace/src/github.com/mattn/go-isatty/doc.go @@ -0,0 +1,2 @@ +// Package isatty implements interface to isatty +package isatty diff --git a/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_bsd.go b/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_bsd.go new file mode 100644 index 00000000..03527475 --- /dev/null +++ b/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_bsd.go @@ -0,0 +1,17 @@ +// +build darwin freebsd + +package isatty + +import ( + "syscall" + "unsafe" +) + +const ioctlReadTermios = syscall.TIOCGETA + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} diff --git a/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_linux.go b/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_linux.go new file mode 100644 index 00000000..8b361d7f --- /dev/null +++ b/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_linux.go @@ -0,0 +1,17 @@ +// +build linux + +package isatty + +import ( + "syscall" + "unsafe" +) + +const ioctlReadTermios = syscall.TCGETS + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} diff --git a/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_windows.go b/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_windows.go new file mode 100644 index 00000000..562ee39c --- /dev/null +++ b/Godeps/_workspace/src/github.com/mattn/go-isatty/isatty_windows.go @@ -0,0 +1,18 @@ +// +build windows + +package isatty + +import ( + "syscall" + "unsafe" +) + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") +var procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + +// IsTerminal return true if the file descriptor is terminal. +func IsTerminal(fd uintptr) bool { + var st uint32 + r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) + return r != 0 && e == 0 +} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/require/doc.go b/Godeps/_workspace/src/github.com/stretchr/testify/require/doc.go deleted file mode 100644 index 7b38438f..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/require/doc.go +++ /dev/null @@ -1,77 +0,0 @@ -// Alternative testing tools which stop test execution if test failed. -// -// Example Usage -// -// The following is a complete example using require in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/require" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// require.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// Assertions -// -// The `require` package have same global functions as in the `assert` package, -// but instead of returning a boolean result they call `t.FailNow()`. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -// -// Here is an overview of the assert functions: -// -// require.Equal(t, expected, actual [, message [, format-args]) -// -// require.NotEqual(t, notExpected, actual [, message [, format-args]]) -// -// require.True(t, actualBool [, message [, format-args]]) -// -// require.False(t, actualBool [, message [, format-args]]) -// -// require.Nil(t, actualObject [, message [, format-args]]) -// -// require.NotNil(t, actualObject [, message [, format-args]]) -// -// require.Empty(t, actualObject [, message [, format-args]]) -// -// require.NotEmpty(t, actualObject [, message [, format-args]]) -// -// require.Error(t, errorObject [, message [, format-args]]) -// -// require.NoError(t, errorObject [, message [, format-args]]) -// -// require.EqualError(t, theError, errString [, message [, format-args]]) -// -// require.Implements(t, (*MyInterface)(nil), new(MyObject) [,message [, format-args]]) -// -// require.IsType(t, expectedObject, actualObject [, message [, format-args]]) -// -// require.Contains(t, string, substring [, message [, format-args]]) -// -// require.NotContains(t, string, substring [, message [, format-args]]) -// -// require.Panics(t, func(){ -// -// // call code that should panic -// -// } [, message [, format-args]]) -// -// require.NotPanics(t, func(){ -// -// // call code that should not panic -// -// } [, message [, format-args]]) -// -// require.WithinDuration(t, timeA, timeB, deltaTime, [, message [, format-args]]) -// -// require.InDelta(t, numA, numB, delta, [, message [, format-args]]) -// -// require.InEpsilon(t, numA, numB, epsilon, [, message [, format-args]]) -package require diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements.go b/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements.go deleted file mode 100644 index 62c75b9c..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements.go +++ /dev/null @@ -1,211 +0,0 @@ -package require - -import ( - "time" - - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" -) - -type Assertions struct { - t TestingT -} - -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { - FailNow(a.t, failureMessage, msgAndArgs...) -} - -// Implements asserts that an object is implemented by the specified interface. - -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - IsType(a.t, expectedType, object, msgAndArgs...) -} - -// Equal asserts that two objects are equal. -// -// require.Equal(123, 123, "123 and 123 should be equal") -func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) { - Equal(a.t, expected, actual, msgAndArgs...) -} - -// Exactly asserts that two objects are equal is value and type. -// -// require.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") -func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) { - Exactly(a.t, expected, actual, msgAndArgs...) -} - -// NotNil asserts that the specified object is not nil. -// -// require.NotNil(err, "err should be something") -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { - NotNil(a.t, object, msgAndArgs...) -} - -// Nil asserts that the specified object is nil. -// -// require.Nil(err, "err should be nothing") -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { - Nil(a.t, object, msgAndArgs...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a -// slice with len == 0. -// -// require.Empty(obj) -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { - Empty(a.t, object, msgAndArgs...) -} - -// Empty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a -// slice with len == 0. -// -// if require.NotEmpty(obj) { -// require.Equal("two", obj[1]) -// } -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { - NotEmpty(a.t, object, msgAndArgs...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// require.Len(mySlice, 3, "The size of slice is not 3") -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { - Len(a.t, object, length, msgAndArgs...) -} - -// True asserts that the specified value is true. -// -// require.True(myBool, "myBool should be true") -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { - True(a.t, value, msgAndArgs...) -} - -// False asserts that the specified value is true. -// -// require.False(myBool, "myBool should be false") -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { - False(a.t, value, msgAndArgs...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// require.NotEqual(obj1, obj2, "two objects shouldn't be equal") -func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) { - NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// Contains asserts that the specified string contains the specified substring. -// -// require.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) { - Contains(a.t, s, contains, msgAndArgs...) -} - -// NotContains asserts that the specified string does NOT contain the specified substring. -// -// require.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) { - NotContains(a.t, s, contains, msgAndArgs...) -} - -// Uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { - Condition(a.t, comp, msgAndArgs...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// require.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - Panics(a.t, f, msgAndArgs...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// require.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - NotPanics(a.t, f, msgAndArgs...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// require.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// require.InDelta(t, math.Pi, (22 / 7.0), 0.01) -func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { - InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if require.NoError(err) { -// require.Equal(actualObj, expectedObj) -// } -func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) { - NoError(a.t, theError, msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if require.Error(err, "An error was expected") { -// require.Equal(err, expectedError) -// } -func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) { - Error(a.t, theError, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if require.Error(err, "An error was expected") { -// require.Equal(err, expectedError) -// } -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { - EqualError(a.t, theError, errString, msgAndArgs...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// require.Regexp(t, regexp.MustCompile("start"), "it's starting") -// require.Regexp(t, "start...$", "it's not starting") -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - Regexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// require.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// require.NotRegexp(t, "^start", "it's not starting") -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - NotRegexp(a.t, rx, str, msgAndArgs...) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go deleted file mode 100644 index 02be2916..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package require - -import ( - "errors" - "testing" - "time" -) - -func TestImplementsWrapper(t *testing.T) { - require := New(t) - - require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestIsTypeWrapper(t *testing.T) { - require := New(t) - require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualWrapper(t *testing.T) { - require := New(t) - require.Equal(1, 1) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Equal(1, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEqualWrapper(t *testing.T) { - require := New(t) - require.NotEqual(1, 2) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotEqual(2, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestExactlyWrapper(t *testing.T) { - require := New(t) - - a := float32(1) - b := float32(1) - c := float64(1) - - require.Exactly(a, b) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Exactly(a, c) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotNilWrapper(t *testing.T) { - require := New(t) - require.NotNil(t, new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotNil(nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNilWrapper(t *testing.T) { - require := New(t) - require.Nil(nil) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Nil(new(AssertionTesterConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestTrueWrapper(t *testing.T) { - require := New(t) - require.True(true) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.True(false) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestFalseWrapper(t *testing.T) { - require := New(t) - require.False(false) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.False(true) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestContainsWrapper(t *testing.T) { - require := New(t) - require.Contains("Hello World", "Hello") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Contains("Hello World", "Salut") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotContainsWrapper(t *testing.T) { - require := New(t) - require.NotContains("Hello World", "Hello!") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotContains("Hello World", "Hello") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestPanicsWrapper(t *testing.T) { - require := New(t) - require.Panics(func() { - panic("Panic!") - }) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Panics(func() {}) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotPanicsWrapper(t *testing.T) { - require := New(t) - require.NotPanics(func() {}) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotPanics(func() { - panic("Panic!") - }) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNoErrorWrapper(t *testing.T) { - require := New(t) - require.NoError(nil) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NoError(errors.New("some error")) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestErrorWrapper(t *testing.T) { - require := New(t) - require.Error(errors.New("some error")) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Error(nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualErrorWrapper(t *testing.T) { - require := New(t) - require.EqualError(errors.New("some error"), "some error") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.EqualError(errors.New("some error"), "Not some error") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEmptyWrapper(t *testing.T) { - require := New(t) - require.Empty("") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Empty("x") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEmptyWrapper(t *testing.T) { - require := New(t) - require.NotEmpty("x") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotEmpty("") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestWithinDurationWrapper(t *testing.T) { - require := New(t) - a := time.Now() - b := a.Add(10 * time.Second) - - require.WithinDuration(a, b, 15*time.Second) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.WithinDuration(a, b, 5*time.Second) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestInDeltaWrapper(t *testing.T) { - require := New(t) - require.InDelta(1.001, 1, 0.01) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.InDelta(1, 2, 0.5) - if !mockT.Failed { - t.Error("Check should fail") - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements.go b/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements.go deleted file mode 100644 index 6b10a611..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements.go +++ /dev/null @@ -1,271 +0,0 @@ -package require - -import ( - "time" - - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" -) - -type TestingT interface { - Errorf(format string, args ...interface{}) - FailNow() -} - -// Fail reports a failure through -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - assert.Fail(t, failureMessage, msgAndArgs...) - t.FailNow() -} - -// Implements asserts that an object is implemented by the specified interface. -// -// require.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { - t.FailNow() - } -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - if !assert.IsType(t, expectedType, object, msgAndArgs...) { - t.FailNow() - } -} - -// Equal asserts that two objects are equal. -// -// require.Equal(t, 123, 123, "123 and 123 should be equal") -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - if !assert.Equal(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// EqualValues asserts that two objects are equal or convertable to each other. -// -// require.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - if !assert.EqualValues(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// Exactly asserts that two objects are equal is value and type. -// -// require.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - if !assert.Exactly(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// NotNil asserts that the specified object is not nil. -// -// require.NotNil(t, err, "err should be something") -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.NotNil(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// Nil asserts that the specified object is nil. -// -// require.Nil(t, err, "err should be nothing") -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.Nil(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// require.Empty(t, obj) -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.Empty(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// require.NotEmpty(t, obj) -// require.Equal(t, "one", obj[0]) -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.NotEmpty(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// require.Len(t, mySlice, 3, "The size of slice is not 3") -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { - if !assert.Len(t, object, length, msgAndArgs...) { - t.FailNow() - } -} - -// True asserts that the specified value is true. -// -// require.True(t, myBool, "myBool should be true") -func True(t TestingT, value bool, msgAndArgs ...interface{}) { - if !assert.True(t, value, msgAndArgs...) { - t.FailNow() - } -} - -// False asserts that the specified value is true. -// -// require.False(t, myBool, "myBool should be false") -func False(t TestingT, value bool, msgAndArgs ...interface{}) { - if !assert.False(t, value, msgAndArgs...) { - t.FailNow() - } -} - -// NotEqual asserts that the specified values are NOT equal. -// -// require.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - if !assert.NotEqual(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// Contains asserts that the specified string contains the specified substring. -// -// require.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) { - if !assert.Contains(t, s, contains, msgAndArgs...) { - t.FailNow() - } -} - -// NotContains asserts that the specified string does NOT contain the specified substring. -// -// require.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) { - if !assert.NotContains(t, s, contains, msgAndArgs...) { - t.FailNow() - } -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { - if !assert.Condition(t, comp, msgAndArgs...) { - t.FailNow() - } -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// require.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if !assert.Panics(t, f, msgAndArgs...) { - t.FailNow() - } -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// require.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if !assert.NotPanics(t, f, msgAndArgs...) { - t.FailNow() - } -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// require.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { - t.FailNow() - } -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// require.InDelta(t, math.Pi, (22 / 7.0), 0.01) -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { - t.FailNow() - } -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { - t.FailNow() - } -} - -// Regexp asserts that a specified regexp matches a string. -// -// require.Regexp(t, regexp.MustCompile("start"), "it's starting") -// require.Regexp(t, "start...$", "it's not starting") -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if !assert.Regexp(t, rx, str, msgAndArgs...) { - t.FailNow() - } -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// require.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// require.NotRegexp(t, "^start", "it's not starting") -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if !assert.NotRegexp(t, rx, str, msgAndArgs...) { - t.FailNow() - } -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// require.NoError(t, err) -// require.Equal(t, actualObj, expectedObj) -// -// Returns whether the assertion was successful (true) or not (false). -func NoError(t TestingT, err error, msgAndArgs ...interface{}) { - if !assert.NoError(t, err, msgAndArgs...) { - t.FailNow() - } -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// require.Error(t, err, "An error was expected") -// require.Equal(t, err, expectedError) -// } -func Error(t TestingT, err error, msgAndArgs ...interface{}) { - if !assert.Error(t, err, msgAndArgs...) { - t.FailNow() - } -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// require.Error(t, err, "An error was expected") -// require.Equal(t, err, expectedError) -// } -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { - if !assert.EqualError(t, theError, errString, msgAndArgs...) { - t.FailNow() - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go deleted file mode 100644 index 9131b2f4..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go +++ /dev/null @@ -1,266 +0,0 @@ -package require - -import ( - "errors" - "testing" - "time" -) - -// AssertionTesterInterface defines an interface to be used for testing assertion methods -type AssertionTesterInterface interface { - TestMethod() -} - -// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface -type AssertionTesterConformingObject struct { -} - -func (a *AssertionTesterConformingObject) TestMethod() { -} - -// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface -type AssertionTesterNonConformingObject struct { -} - -type MockT struct { - Failed bool -} - -func (t *MockT) FailNow() { - t.Failed = true -} - -func (t *MockT) Errorf(format string, args ...interface{}) { - _, _ = format, args -} - -func TestImplements(t *testing.T) { - - Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestIsType(t *testing.T) { - - IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqual(t *testing.T) { - - Equal(t, 1, 1) - - mockT := new(MockT) - Equal(mockT, 1, 2) - if !mockT.Failed { - t.Error("Check should fail") - } - -} - -func TestNotEqual(t *testing.T) { - - NotEqual(t, 1, 2) - mockT := new(MockT) - NotEqual(mockT, 2, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestExactly(t *testing.T) { - - a := float32(1) - b := float32(1) - c := float64(1) - - Exactly(t, a, b) - - mockT := new(MockT) - Exactly(mockT, a, c) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotNil(t *testing.T) { - - NotNil(t, new(AssertionTesterConformingObject)) - - mockT := new(MockT) - NotNil(mockT, nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNil(t *testing.T) { - - Nil(t, nil) - - mockT := new(MockT) - Nil(mockT, new(AssertionTesterConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestTrue(t *testing.T) { - - True(t, true) - - mockT := new(MockT) - True(mockT, false) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestFalse(t *testing.T) { - - False(t, false) - - mockT := new(MockT) - False(mockT, true) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestContains(t *testing.T) { - - Contains(t, "Hello World", "Hello") - - mockT := new(MockT) - Contains(mockT, "Hello World", "Salut") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotContains(t *testing.T) { - - NotContains(t, "Hello World", "Hello!") - - mockT := new(MockT) - NotContains(mockT, "Hello World", "Hello") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestPanics(t *testing.T) { - - Panics(t, func() { - panic("Panic!") - }) - - mockT := new(MockT) - Panics(mockT, func() {}) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotPanics(t *testing.T) { - - NotPanics(t, func() {}) - - mockT := new(MockT) - NotPanics(mockT, func() { - panic("Panic!") - }) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNoError(t *testing.T) { - - NoError(t, nil) - - mockT := new(MockT) - NoError(mockT, errors.New("some error")) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestError(t *testing.T) { - - Error(t, errors.New("some error")) - - mockT := new(MockT) - Error(mockT, nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualError(t *testing.T) { - - EqualError(t, errors.New("some error"), "some error") - - mockT := new(MockT) - EqualError(mockT, errors.New("some error"), "Not some error") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEmpty(t *testing.T) { - - Empty(t, "") - - mockT := new(MockT) - Empty(mockT, "x") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEmpty(t *testing.T) { - - NotEmpty(t, "x") - - mockT := new(MockT) - NotEmpty(mockT, "") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestWithinDuration(t *testing.T) { - - a := time.Now() - b := a.Add(10 * time.Second) - - WithinDuration(t, a, b, 15*time.Second) - - mockT := new(MockT) - WithinDuration(mockT, a, b, 5*time.Second) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestInDelta(t *testing.T) { - - InDelta(t, 1.001, 1, 0.01) - - mockT := new(MockT) - InDelta(mockT, 1, 2, 0.5) - if !mockT.Failed { - t.Error("Check should fail") - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/suite/doc.go b/Godeps/_workspace/src/github.com/stretchr/testify/suite/doc.go deleted file mode 100644 index 3731eaa3..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/suite/doc.go +++ /dev/null @@ -1,65 +0,0 @@ -// The suite package contains logic for creating testing suite structs -// and running the methods on those structs as tests. The most useful -// piece of this package is that you can create setup/teardown methods -// on your testing suites, which will run before/after the whole suite -// or individual tests (depending on which interface(s) you -// implement). -// -// A testing suite is usually built by first extending the built-in -// suite functionality from suite.Suite in testify. Alternatively, -// you could reproduce that logic on your own if you wanted (you -// just need to implement the TestingSuite interface from -// suite/interfaces.go). -// -// After that, you can implement any of the interfaces in -// suite/interfaces.go to add setup/teardown functionality to your -// suite, and add any methods that start with "Test" to add tests. -// Methods that do not match any suite interfaces and do not begin -// with "Test" will not be run by testify, and can safely be used as -// helper methods. -// -// Once you've built your testing suite, you need to run the suite -// (using suite.Run from testify) inside any function that matches the -// identity that "go test" is already looking for (i.e. -// func(*testing.T)). -// -// Regular expression to select test suites specified command-line -// argument "-run". Regular expression to select the methods -// of test suites specified command-line argument "-m". -// Suite object has assertion methods. -// -// A crude example: -// // Basic imports -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// "github.com/stretchr/testify/suite" -// ) -// -// // Define the suite, and absorb the built-in basic suite -// // functionality from testify - including a T() method which -// // returns the current testing context -// type ExampleTestSuite struct { -// suite.Suite -// VariableThatShouldStartAtFive int -// } -// -// // Make sure that VariableThatShouldStartAtFive is set to five -// // before each test -// func (suite *ExampleTestSuite) SetupTest() { -// suite.VariableThatShouldStartAtFive = 5 -// } -// -// // All methods that begin with "Test" are run as tests within a -// // suite. -// func (suite *ExampleTestSuite) TestExample() { -// assert.Equal(suite.T(), suite.VariableThatShouldStartAtFive, 5) -// suite.Equal(suite.VariableThatShouldStartAtFive, 5) -// } -// -// // In order for 'go test' to run this suite, we need to create -// // a normal test function and pass our suite to suite.Run -// func TestExampleTestSuite(t *testing.T) { -// suite.Run(t, new(ExampleTestSuite)) -// } -package suite diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/suite/interfaces.go b/Godeps/_workspace/src/github.com/stretchr/testify/suite/interfaces.go deleted file mode 100644 index 20969472..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/suite/interfaces.go +++ /dev/null @@ -1,34 +0,0 @@ -package suite - -import "testing" - -// TestingSuite can store and return the current *testing.T context -// generated by 'go test'. -type TestingSuite interface { - T() *testing.T - SetT(*testing.T) -} - -// SetupAllSuite has a SetupSuite method, which will run before the -// tests in the suite are run. -type SetupAllSuite interface { - SetupSuite() -} - -// SetupTestSuite has a SetupTest method, which will run before each -// test in the suite. -type SetupTestSuite interface { - SetupTest() -} - -// TearDownAllSuite has a TearDownSuite method, which will run after -// all the tests in the suite have been run. -type TearDownAllSuite interface { - TearDownSuite() -} - -// TearDownTestSuite has a TearDownTest method, which will run after -// each test in the suite. -type TearDownTestSuite interface { - TearDownTest() -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/suite/suite.go b/Godeps/_workspace/src/github.com/stretchr/testify/suite/suite.go deleted file mode 100644 index 4dbe6eca..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/suite/suite.go +++ /dev/null @@ -1,114 +0,0 @@ -package suite - -import ( - "flag" - "fmt" - "os" - "reflect" - "regexp" - "testing" - - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/require" -) - -var matchMethod = flag.String("m", "", "regular expression to select tests of the suite to run") - -// Suite is a basic testing suite with methods for storing and -// retrieving the current *testing.T context. -type Suite struct { - *assert.Assertions - require *require.Assertions - t *testing.T -} - -// T retrieves the current *testing.T context. -func (suite *Suite) T() *testing.T { - return suite.t -} - -// SetT sets the current *testing.T context. -func (suite *Suite) SetT(t *testing.T) { - suite.t = t - suite.Assertions = assert.New(t) -} - -// Require returns a require context for suite. -func (suite *Suite) Require() *require.Assertions { - if suite.require == nil { - suite.require = require.New(suite.T()) - } - return suite.require -} - -// Assert returns an assert context for suite. Normally, you can call -// `suite.NoError(expected, actual)`, but for situations where the embedded -// methods are overridden (for example, you might want to override -// assert.Assertions with require.Assertions), this method is provided so you -// can call `suite.Assert().NoError()`. -func (suite *Suite) Assert() *assert.Assertions { - if suite.Assertions == nil { - suite.Assertions = assert.New(suite.T()) - } - return suite.Assertions -} - -// Run takes a testing suite and runs all of the tests attached -// to it. -func Run(t *testing.T, suite TestingSuite) { - suite.SetT(t) - - if setupAllSuite, ok := suite.(SetupAllSuite); ok { - setupAllSuite.SetupSuite() - } - defer func() { - if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { - tearDownAllSuite.TearDownSuite() - } - }() - - methodFinder := reflect.TypeOf(suite) - tests := []testing.InternalTest{} - for index := 0; index < methodFinder.NumMethod(); index++ { - method := methodFinder.Method(index) - ok, err := methodFilter(method.Name) - if err != nil { - fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) - os.Exit(1) - } - if ok { - test := testing.InternalTest{ - Name: method.Name, - F: func(t *testing.T) { - parentT := suite.T() - suite.SetT(t) - if setupTestSuite, ok := suite.(SetupTestSuite); ok { - setupTestSuite.SetupTest() - } - defer func() { - if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { - tearDownTestSuite.TearDownTest() - } - suite.SetT(parentT) - }() - method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) - }, - } - tests = append(tests, test) - } - } - - if !testing.RunTests(func(_, _ string) (bool, error) { return true, nil }, - tests) { - t.Fail() - } -} - -// Filtering method according to set regular expression -// specified command-line argument -m -func methodFilter(name string) (bool, error) { - if ok, _ := regexp.MatchString("^Test", name); !ok { - return false, nil - } - return regexp.MatchString(*matchMethod, name) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/suite/suite_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/suite/suite_test.go deleted file mode 100644 index 630c5869..00000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/suite/suite_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package suite - -import ( - "errors" - "io/ioutil" - "os" - "testing" - - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" -) - -// This suite is intended to store values to make sure that only -// testing-suite-related methods are run. It's also a fully -// functional example of a testing suite, using setup/teardown methods -// and a helper method that is ignored by testify. To make this look -// more like a real world example, all tests in the suite perform some -// type of assertion. -type SuiteTester struct { - // Include our basic suite logic. - Suite - - // Keep counts of how many times each method is run. - SetupSuiteRunCount int - TearDownSuiteRunCount int - SetupTestRunCount int - TearDownTestRunCount int - TestOneRunCount int - TestTwoRunCount int - NonTestMethodRunCount int -} - -type SuiteSkipTester struct { - // Include our basic suite logic. - Suite - - // Keep counts of how many times each method is run. - SetupSuiteRunCount int - TearDownSuiteRunCount int -} - -// The SetupSuite method will be run by testify once, at the very -// start of the testing suite, before any tests are run. -func (suite *SuiteTester) SetupSuite() { - suite.SetupSuiteRunCount++ -} - -func (suite *SuiteSkipTester) SetupSuite() { - suite.SetupSuiteRunCount++ - suite.T().Skip() -} - -// The TearDownSuite method will be run by testify once, at the very -// end of the testing suite, after all tests have been run. -func (suite *SuiteTester) TearDownSuite() { - suite.TearDownSuiteRunCount++ -} - -func (suite *SuiteSkipTester) TearDownSuite() { - suite.TearDownSuiteRunCount++ -} - -// The SetupTest method will be run before every test in the suite. -func (suite *SuiteTester) SetupTest() { - suite.SetupTestRunCount++ -} - -// The TearDownTest method will be run after every test in the suite. -func (suite *SuiteTester) TearDownTest() { - suite.TearDownTestRunCount++ -} - -// Every method in a testing suite that begins with "Test" will be run -// as a test. TestOne is an example of a test. For the purposes of -// this example, we've included assertions in the tests, since most -// tests will issue assertions. -func (suite *SuiteTester) TestOne() { - beforeCount := suite.TestOneRunCount - suite.TestOneRunCount++ - assert.Equal(suite.T(), suite.TestOneRunCount, beforeCount+1) - suite.Equal(suite.TestOneRunCount, beforeCount+1) -} - -// TestTwo is another example of a test. -func (suite *SuiteTester) TestTwo() { - beforeCount := suite.TestTwoRunCount - suite.TestTwoRunCount++ - assert.NotEqual(suite.T(), suite.TestTwoRunCount, beforeCount) - suite.NotEqual(suite.TestTwoRunCount, beforeCount) -} - -func (suite *SuiteTester) TestSkip() { - suite.T().Skip() -} - -// NonTestMethod does not begin with "Test", so it will not be run by -// testify as a test in the suite. This is useful for creating helper -// methods for your tests. -func (suite *SuiteTester) NonTestMethod() { - suite.NonTestMethodRunCount++ -} - -// TestRunSuite will be run by the 'go test' command, so within it, we -// can run our suite using the Run(*testing.T, TestingSuite) function. -func TestRunSuite(t *testing.T) { - suiteTester := new(SuiteTester) - Run(t, suiteTester) - - // Normally, the test would end here. The following are simply - // some assertions to ensure that the Run function is working as - // intended - they are not part of the example. - - // The suite was only run once, so the SetupSuite and TearDownSuite - // methods should have each been run only once. - assert.Equal(t, suiteTester.SetupSuiteRunCount, 1) - assert.Equal(t, suiteTester.TearDownSuiteRunCount, 1) - - // There are three test methods (TestOne, TestTwo, and TestSkip), so - // the SetupTest and TearDownTest methods (which should be run once for - // each test) should have been run three times. - assert.Equal(t, suiteTester.SetupTestRunCount, 3) - assert.Equal(t, suiteTester.TearDownTestRunCount, 3) - - // Each test should have been run once. - assert.Equal(t, suiteTester.TestOneRunCount, 1) - assert.Equal(t, suiteTester.TestTwoRunCount, 1) - - // Methods that don't match the test method identifier shouldn't - // have been run at all. - assert.Equal(t, suiteTester.NonTestMethodRunCount, 0) - - suiteSkipTester := new(SuiteSkipTester) - Run(t, suiteSkipTester) - - // The suite was only run once, so the SetupSuite and TearDownSuite - // methods should have each been run only once, even though SetupSuite - // called Skip() - assert.Equal(t, suiteSkipTester.SetupSuiteRunCount, 1) - assert.Equal(t, suiteSkipTester.TearDownSuiteRunCount, 1) - -} - -func TestSuiteGetters(t *testing.T) { - suite := new(SuiteTester) - suite.SetT(t) - assert.NotNil(t, suite.Assert()) - assert.Equal(t, suite.Assertions, suite.Assert()) - assert.NotNil(t, suite.Require()) - assert.Equal(t, suite.require, suite.Require()) -} - -type SuiteLoggingTester struct { - Suite -} - -func (s *SuiteLoggingTester) TestLoggingPass() { - s.T().Log("TESTLOGPASS") -} - -func (s *SuiteLoggingTester) TestLoggingFail() { - s.T().Log("TESTLOGFAIL") - assert.NotNil(s.T(), nil) // expected to fail -} - -type StdoutCapture struct { - oldStdout *os.File - readPipe *os.File -} - -func (sc *StdoutCapture) StartCapture() { - sc.oldStdout = os.Stdout - sc.readPipe, os.Stdout, _ = os.Pipe() -} - -func (sc *StdoutCapture) StopCapture() (string, error) { - if sc.oldStdout == nil || sc.readPipe == nil { - return "", errors.New("StartCapture not called before StopCapture") - } - os.Stdout.Close() - os.Stdout = sc.oldStdout - bytes, err := ioutil.ReadAll(sc.readPipe) - if err != nil { - return "", err - } - return string(bytes), nil -} - -func TestSuiteLogging(t *testing.T) { - testT := testing.T{} - - suiteLoggingTester := new(SuiteLoggingTester) - - capture := StdoutCapture{} - capture.StartCapture() - Run(&testT, suiteLoggingTester) - output, err := capture.StopCapture() - - assert.Nil(t, err, "Got an error trying to capture stdout!") - - // Failed tests' output is always printed - assert.Contains(t, output, "TESTLOGFAIL") - - if testing.Verbose() { - // In verbose mode, output from successful tests is also printed - assert.Contains(t, output, "TESTLOGPASS") - } else { - assert.NotContains(t, output, "TESTLOGPASS") - } -} diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/LICENSE b/Godeps/_workspace/src/github.com/tendermint/go-rpc/LICENSE new file mode 100644 index 00000000..8dada3ed --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/README.md b/Godeps/_workspace/src/github.com/tendermint/go-rpc/README.md new file mode 100644 index 00000000..e74cf802 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/README.md @@ -0,0 +1,4 @@ +# go-rpc + +HTTP RPC server supporting calls via uri params, jsonrpc, and jsonrpc over websockets + diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/http_client.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/http_client.go new file mode 100644 index 00000000..b483e49c --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/http_client.go @@ -0,0 +1,169 @@ +package rpcclient + +import ( + "bytes" + "encoding/json" + "errors" + "io/ioutil" + "net" + "net/http" + "net/url" + "strings" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-rpc/types" + "github.com/tendermint/go-wire" +) + +func unixDial(proto, addr string) (conn net.Conn, err error) { + return net.Dial("unix", addr) +} + +func tcpDial(proto, addr string) (conn net.Conn, err error) { + return net.Dial("tcp", addr) +} + +func socketTransport(remote string) *http.Transport { + if rpctypes.SocketType(remote) == "unix" { + return &http.Transport{ + Dial: unixDial, + } + } else { + return &http.Transport{ + Dial: tcpDial, + } + } +} + +//------------------------------------------------------------------------------------ + +// JSON rpc takes params as a slice +type ClientJSONRPC struct { + remote string + client *http.Client +} + +func NewClientJSONRPC(remote string) *ClientJSONRPC { + return &ClientJSONRPC{ + remote: remote, + client: &http.Client{Transport: socketTransport(remote)}, + } +} + +func (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) { + return c.call(method, params, result) +} + +func (c *ClientJSONRPC) call(method string, params []interface{}, result interface{}) (interface{}, error) { + // Make request and get responseBytes + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: method, + Params: params, + ID: "", + } + requestBytes := wire.JSONBytes(request) + requestBuf := bytes.NewBuffer(requestBytes) + log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes))) + httpResponse, err := c.client.Post(c.remote, "text/json", requestBuf) + if err != nil { + return nil, err + } + defer httpResponse.Body.Close() + responseBytes, err := ioutil.ReadAll(httpResponse.Body) + if err != nil { + return nil, err + } + log.Info(Fmt("RPC response: %v", string(responseBytes))) + return unmarshalResponseBytes(responseBytes, result) +} + +//------------------------------------------------------------- + +// URI takes params as a map +type ClientURI struct { + remote string + client *http.Client +} + +func NewClientURI(remote string) *ClientURI { + if !strings.HasSuffix(remote, "/") { + remote = remote + "/" + } + return &ClientURI{ + remote: remote, + client: &http.Client{Transport: socketTransport(remote)}, + } +} + +func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { + return c.call(method, params, result) +} + +func (c *ClientURI) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { + values, err := argsToURLValues(params) + if err != nil { + return nil, err + } + log.Info(Fmt("URI request to %v (%v): %v", c.remote, method, values)) + resp, err := c.client.PostForm(c.remote+method, values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + responseBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return unmarshalResponseBytes(responseBytes, result) +} + +//------------------------------------------------ + +func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface{}, error) { + // read response + // if rpc/core/types is imported, the result will unmarshal + // into the correct type + var err error + response := &rpctypes.RPCResponse{} + err = json.Unmarshal(responseBytes, response) + if err != nil { + return nil, err + } + errorStr := response.Error + if errorStr != "" { + return nil, errors.New(errorStr) + } + // unmarshal the RawMessage into the result + result = wire.ReadJSONPtr(result, *response.Result, &err) + return result, err +} + +func argsToURLValues(args map[string]interface{}) (url.Values, error) { + values := make(url.Values) + if len(args) == 0 { + return values, nil + } + err := argsToJson(args) + if err != nil { + return nil, err + } + for key, val := range args { + values.Set(key, val.(string)) + } + return values, nil +} + +func argsToJson(args map[string]interface{}) error { + var n int + var err error + for k, v := range args { + buf := new(bytes.Buffer) + wire.WriteJSON(v, buf, &n, &err) + if err != nil { + return err + } + args[k] = buf.String() + } + return nil +} diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/log.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/log.go new file mode 100644 index 00000000..bfebc78d --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/log.go @@ -0,0 +1,7 @@ +package rpcclient + +import ( + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" +) + +var log = log15.New("module", "rpcclient") diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/ws_client.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/ws_client.go new file mode 100644 index 00000000..90202605 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/client/ws_client.go @@ -0,0 +1,129 @@ +package rpcclient + +import ( + "encoding/json" + "fmt" + "net/http" + "time" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gorilla/websocket" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-rpc/types" +) + +const ( + wsResultsChannelCapacity = 10 + wsErrorsChannelCapacity = 1 + wsWriteTimeoutSeconds = 10 +) + +type WSClient struct { + QuitService + Address string + *websocket.Conn + ResultsCh chan json.RawMessage // closes upon WSClient.Stop() + ErrorsCh chan error // closes upon WSClient.Stop() +} + +// create a new connection +func NewWSClient(addr string) *WSClient { + wsClient := &WSClient{ + Address: addr, + Conn: nil, + ResultsCh: make(chan json.RawMessage, wsResultsChannelCapacity), + ErrorsCh: make(chan error, wsErrorsChannelCapacity), + } + wsClient.QuitService = *NewQuitService(log, "WSClient", wsClient) + return wsClient +} + +func (wsc *WSClient) String() string { + return wsc.Address +} + +func (wsc *WSClient) OnStart() error { + wsc.QuitService.OnStart() + err := wsc.dial() + if err != nil { + return err + } + go wsc.receiveEventsRoutine() + return nil +} + +func (wsc *WSClient) dial() error { + // Dial + dialer := websocket.DefaultDialer + rHeader := http.Header{} + con, _, err := dialer.Dial(wsc.Address, rHeader) + if err != nil { + return err + } + // Set the ping/pong handlers + con.SetPingHandler(func(m string) error { + // NOTE: https://github.com/gorilla/websocket/issues/97 + go con.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) + return nil + }) + con.SetPongHandler(func(m string) error { + // NOTE: https://github.com/gorilla/websocket/issues/97 + return nil + }) + wsc.Conn = con + return nil +} + +func (wsc *WSClient) OnStop() { + wsc.QuitService.OnStop() + // ResultsCh/ErrorsCh is closed in receiveEventsRoutine. +} + +func (wsc *WSClient) receiveEventsRoutine() { + for { + _, data, err := wsc.ReadMessage() + if err != nil { + log.Info("WSClient failed to read message", "error", err, "data", string(data)) + wsc.Stop() + break + } else { + var response rpctypes.RPCResponse + err := json.Unmarshal(data, &response) + if err != nil { + log.Info("WSClient failed to parse message", "error", err, "data", string(data)) + wsc.ErrorsCh <- err + continue + } + if response.Error != "" { + wsc.ErrorsCh <- fmt.Errorf(response.Error) + continue + } + wsc.ResultsCh <- *response.Result + } + } + + // Cleanup + close(wsc.ResultsCh) + close(wsc.ErrorsCh) +} + +// subscribe to an event +func (wsc *WSClient) Subscribe(eventid string) error { + err := wsc.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "subscribe", + Params: []interface{}{eventid}, + }) + return err +} + +// unsubscribe from an event +func (wsc *WSClient) Unsubscribe(eventid string) error { + err := wsc.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "unsubscribe", + Params: []interface{}{eventid}, + }) + return err +} diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/handlers.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/handlers.go new file mode 100644 index 00000000..d8490d5e --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/handlers.go @@ -0,0 +1,563 @@ +package rpcserver + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "reflect" + "sort" + "strings" + "time" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gorilla/websocket" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-events" + . "github.com/tendermint/go-rpc/types" + "github.com/tendermint/go-wire" +) + +// Adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions. +// "result" is the interface on which the result objects are registered, and is popualted with every RPCResponse +func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc) { + // HTTP endpoints + for funcName, rpcFunc := range funcMap { + mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc)) + } + + // JSONRPC endpoints + mux.HandleFunc("/", makeJSONRPCHandler(funcMap)) +} + +//------------------------------------- +// function introspection + +// holds all type information for each function +type RPCFunc struct { + f reflect.Value // underlying rpc function + args []reflect.Type // type of each function arg + returns []reflect.Type // type of each return arg + argNames []string // name of each argument + ws bool // websocket only +} + +// wraps a function for quicker introspection +// f is the function, args are comma separated argument names +func NewRPCFunc(f interface{}, args string) *RPCFunc { + return newRPCFunc(f, args, false) +} + +func NewWSRPCFunc(f interface{}, args string) *RPCFunc { + return newRPCFunc(f, args, true) +} + +func newRPCFunc(f interface{}, args string, ws bool) *RPCFunc { + var argNames []string + if args != "" { + argNames = strings.Split(args, ",") + } + return &RPCFunc{ + f: reflect.ValueOf(f), + args: funcArgTypes(f), + returns: funcReturnTypes(f), + argNames: argNames, + ws: ws, + } +} + +// return a function's argument types +func funcArgTypes(f interface{}) []reflect.Type { + t := reflect.TypeOf(f) + n := t.NumIn() + typez := make([]reflect.Type, n) + for i := 0; i < n; i++ { + typez[i] = t.In(i) + } + return typez +} + +// return a function's return types +func funcReturnTypes(f interface{}) []reflect.Type { + t := reflect.TypeOf(f) + n := t.NumOut() + typez := make([]reflect.Type, n) + for i := 0; i < n; i++ { + typez[i] = t.Out(i) + } + return typez +} + +// function introspection +//----------------------------------------------------------------------------- +// rpc.json + +// jsonrpc calls grab the given method's function info and runs reflect.Call +func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + b, _ := ioutil.ReadAll(r.Body) + // if its an empty request (like from a browser), + // just display a list of functions + if len(b) == 0 { + writeListOfEndpoints(w, r, funcMap) + return + } + + var request RPCRequest + err := json.Unmarshal(b, &request) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + return + } + if len(r.URL.Path) > 1 { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) + return + } + rpcFunc := funcMap[request.Method] + if rpcFunc == nil { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) + return + } + if rpcFunc.ws { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) + return + } + args, err := jsonParamsToArgs(rpcFunc, request.Params) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, err.Error())) + return + } + returns := rpcFunc.f.Call(args) + log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) + result, err := unreflectResult(returns) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, err.Error())) + return + } + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, "")) + } +} + +// Convert a list of interfaces to properly typed values +func jsonParamsToArgs(rpcFunc *RPCFunc, params []interface{}) ([]reflect.Value, error) { + if len(rpcFunc.argNames) != len(params) { + return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)) + } + values := make([]reflect.Value, len(params)) + for i, p := range params { + ty := rpcFunc.args[i] + v, err := _jsonObjectToArg(ty, p) + if err != nil { + return nil, err + } + values[i] = v + } + return values, nil +} + +// Same as above, but with the first param the websocket connection +func jsonParamsToArgsWS(rpcFunc *RPCFunc, params []interface{}, wsCtx WSRPCContext) ([]reflect.Value, error) { + if len(rpcFunc.argNames) != len(params) { + return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames)-1, rpcFunc.argNames[1:], len(params), params)) + } + values := make([]reflect.Value, len(params)+1) + values[0] = reflect.ValueOf(wsCtx) + for i, p := range params { + ty := rpcFunc.args[i+1] + v, err := _jsonObjectToArg(ty, p) + if err != nil { + return nil, err + } + values[i+1] = v + } + return values, nil +} + +func _jsonObjectToArg(ty reflect.Type, object interface{}) (reflect.Value, error) { + var err error + v := reflect.New(ty) + wire.ReadJSONObjectPtr(v.Interface(), object, &err) + if err != nil { + return v, err + } + v = v.Elem() + return v, nil +} + +// rpc.json +//----------------------------------------------------------------------------- +// rpc.http + +// convert from a function name to the http handler +func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) { + // Exception for websocket endpoints + if rpcFunc.ws { + return func(w http.ResponseWriter, r *http.Request) { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, "This RPC method is only for websockets")) + } + } + // All other endpoints + return func(w http.ResponseWriter, r *http.Request) { + args, err := httpParamsToArgs(rpcFunc, r) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + return + } + returns := rpcFunc.f.Call(args) + log.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) + result, err := unreflectResult(returns) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + return + } + WriteRPCResponseHTTP(w, NewRPCResponse("", result, "")) + } +} + +// Covert an http query to a list of properly typed values. +// To be properly decoded the arg must be a concrete type from tendermint (if its an interface). +func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error) { + argTypes := rpcFunc.args + argNames := rpcFunc.argNames + + var err error + values := make([]reflect.Value, len(argNames)) + for i, name := range argNames { + ty := argTypes[i] + arg := GetParam(r, name) + values[i], err = _jsonStringToArg(ty, arg) + if err != nil { + return nil, err + } + } + return values, nil +} + +func _jsonStringToArg(ty reflect.Type, arg string) (reflect.Value, error) { + var err error + v := reflect.New(ty) + wire.ReadJSONPtr(v.Interface(), []byte(arg), &err) + if err != nil { + return v, err + } + v = v.Elem() + return v, nil +} + +// rpc.http +//----------------------------------------------------------------------------- +// rpc.websocket + +const ( + writeChanCapacity = 1000 + wsWriteTimeoutSeconds = 30 // each write times out after this + wsReadTimeoutSeconds = 30 // connection times out if we haven't received *anything* in this long, not even pings. + wsPingTickerSeconds = 10 // send a ping every PingTickerSeconds. +) + +// a single websocket connection +// contains listener id, underlying ws connection, +// and the event switch for subscribing to events +type wsConnection struct { + QuitService + + remoteAddr string + baseConn *websocket.Conn + writeChan chan RPCResponse + readTimeout *time.Timer + pingTicker *time.Ticker + + funcMap map[string]*RPCFunc + evsw *events.EventSwitch +} + +// new websocket connection wrapper +func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw *events.EventSwitch) *wsConnection { + wsc := &wsConnection{ + remoteAddr: baseConn.RemoteAddr().String(), + baseConn: baseConn, + writeChan: make(chan RPCResponse, writeChanCapacity), // error when full. + funcMap: funcMap, + evsw: evsw, + } + wsc.QuitService = *NewQuitService(log, "wsConnection", wsc) + return wsc +} + +// wsc.Start() blocks until the connection closes. +func (wsc *wsConnection) OnStart() error { + wsc.QuitService.OnStart() + + // Read subscriptions/unsubscriptions to events + go wsc.readRoutine() + + // Custom Ping handler to touch readTimeout + wsc.readTimeout = time.NewTimer(time.Second * wsReadTimeoutSeconds) + wsc.pingTicker = time.NewTicker(time.Second * wsPingTickerSeconds) + wsc.baseConn.SetPingHandler(func(m string) error { + // NOTE: https://github.com/gorilla/websocket/issues/97 + go wsc.baseConn.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) + wsc.readTimeout.Reset(time.Second * wsReadTimeoutSeconds) + return nil + }) + wsc.baseConn.SetPongHandler(func(m string) error { + // NOTE: https://github.com/gorilla/websocket/issues/97 + wsc.readTimeout.Reset(time.Second * wsReadTimeoutSeconds) + return nil + }) + go wsc.readTimeoutRoutine() + + // Write responses, BLOCKING. + wsc.writeRoutine() + return nil +} + +func (wsc *wsConnection) OnStop() { + wsc.QuitService.OnStop() + wsc.evsw.RemoveListener(wsc.remoteAddr) + wsc.readTimeout.Stop() + wsc.pingTicker.Stop() + // The write loop closes the websocket connection + // when it exits its loop, and the read loop + // closes the writeChan +} + +func (wsc *wsConnection) readTimeoutRoutine() { + select { + case <-wsc.readTimeout.C: + log.Notice("Stopping connection due to read timeout") + wsc.Stop() + case <-wsc.Quit: + return + } +} + +// Implements WSRPCConnection +func (wsc *wsConnection) GetRemoteAddr() string { + return wsc.remoteAddr +} + +// Implements WSRPCConnection +func (wsc *wsConnection) GetEventSwitch() *events.EventSwitch { + return wsc.evsw +} + +// Implements WSRPCConnection +// Blocking write to writeChan until service stops. +// Goroutine-safe +func (wsc *wsConnection) WriteRPCResponse(resp RPCResponse) { + select { + case <-wsc.Quit: + return + case wsc.writeChan <- resp: + } +} + +// Implements WSRPCConnection +// Nonblocking write. +// Goroutine-safe +func (wsc *wsConnection) TryWriteRPCResponse(resp RPCResponse) bool { + select { + case <-wsc.Quit: + return false + case wsc.writeChan <- resp: + return true + default: + return false + } +} + +// Read from the socket and subscribe to or unsubscribe from events +func (wsc *wsConnection) readRoutine() { + // Do not close writeChan, to allow WriteRPCResponse() to fail. + // defer close(wsc.writeChan) + + for { + select { + case <-wsc.Quit: + return + default: + var in []byte + // Do not set a deadline here like below: + // wsc.baseConn.SetReadDeadline(time.Now().Add(time.Second * wsReadTimeoutSeconds)) + // The client may not send anything for a while. + // We use `readTimeout` to handle read timeouts. + _, in, err := wsc.baseConn.ReadMessage() + if err != nil { + log.Notice("Failed to read from connection", "remote", wsc.remoteAddr) + // an error reading the connection, + // kill the connection + wsc.Stop() + return + } + var request RPCRequest + err = json.Unmarshal(in, &request) + if err != nil { + errStr := fmt.Sprintf("Error unmarshaling data: %s", err.Error()) + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, errStr)) + continue + } + + // Now, fetch the RPCFunc and execute it. + + rpcFunc := wsc.funcMap[request.Method] + if rpcFunc == nil { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) + continue + } + var args []reflect.Value + if rpcFunc.ws { + wsCtx := WSRPCContext{Request: request, WSRPCConnection: wsc} + args, err = jsonParamsToArgsWS(rpcFunc, request.Params, wsCtx) + } else { + args, err = jsonParamsToArgs(rpcFunc, request.Params) + } + if err != nil { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) + continue + } + returns := rpcFunc.f.Call(args) + log.Info("WSJSONRPC", "method", request.Method, "args", args, "returns", returns) + result, err := unreflectResult(returns) + if err != nil { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) + continue + } else { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, result, "")) + continue + } + + } + } +} + +// receives on a write channel and writes out on the socket +func (wsc *wsConnection) writeRoutine() { + defer wsc.baseConn.Close() + for { + select { + case <-wsc.Quit: + return + case <-wsc.pingTicker.C: + err := wsc.baseConn.WriteMessage(websocket.PingMessage, []byte{}) + if err != nil { + log.Error("Failed to write ping message on websocket", "error", err) + wsc.Stop() + return + } + case msg := <-wsc.writeChan: + jsonBytes, err := json.Marshal(msg) + if err != nil { + log.Error("Failed to marshal RPCResponse to JSON", "error", err) + } else { + wsc.baseConn.SetWriteDeadline(time.Now().Add(time.Second * wsWriteTimeoutSeconds)) + if err = wsc.baseConn.WriteMessage(websocket.TextMessage, jsonBytes); err != nil { + log.Warn("Failed to write response on websocket", "error", err) + wsc.Stop() + return + } + } + } + } +} + +//---------------------------------------- + +// Main manager for all websocket connections +// Holds the event switch +// NOTE: The websocket path is defined externally, e.g. in node/node.go +type WebsocketManager struct { + websocket.Upgrader + funcMap map[string]*RPCFunc + evsw *events.EventSwitch +} + +func NewWebsocketManager(funcMap map[string]*RPCFunc, evsw *events.EventSwitch) *WebsocketManager { + return &WebsocketManager{ + funcMap: funcMap, + evsw: evsw, + Upgrader: websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + CheckOrigin: func(r *http.Request) bool { + // TODO + return true + }, + }, + } +} + +// Upgrade the request/response (via http.Hijack) and starts the wsConnection. +func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Request) { + wsConn, err := wm.Upgrade(w, r, nil) + if err != nil { + // TODO - return http error + log.Error("Failed to upgrade to websocket connection", "error", err) + return + } + + // register connection + con := NewWSConnection(wsConn, wm.funcMap, wm.evsw) + log.Notice("New websocket connection", "remote", con.remoteAddr) + con.Start() // Blocking +} + +// rpc.websocket +//----------------------------------------------------------------------------- + +// NOTE: assume returns is result struct and error. If error is not nil, return it +func unreflectResult(returns []reflect.Value) (interface{}, error) { + errV := returns[1] + if errV.Interface() != nil { + return nil, fmt.Errorf("%v", errV.Interface()) + } + rv := returns[0] + // the result is a registered interface, + // we need a pointer to it so we can marshal with type byte + rvp := reflect.New(rv.Type()) + rvp.Elem().Set(rv) + return rvp.Interface(), nil +} + +// writes a list of available rpc endpoints as an html page +func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) { + noArgNames := []string{} + argNames := []string{} + for name, funcData := range funcMap { + if len(funcData.args) == 0 { + noArgNames = append(noArgNames, name) + } else { + argNames = append(argNames, name) + } + } + sort.Strings(noArgNames) + sort.Strings(argNames) + buf := new(bytes.Buffer) + buf.WriteString("<html><body>") + buf.WriteString("<br>Available endpoints:<br>") + + for _, name := range noArgNames { + link := fmt.Sprintf("http://%s/%s", r.Host, name) + buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link)) + } + + buf.WriteString("<br>Endpoints that require arguments:<br>") + for _, name := range argNames { + link := fmt.Sprintf("http://%s/%s?", r.Host, name) + funcData := funcMap[name] + for i, argName := range funcData.argNames { + link += argName + "=_" + if i < len(funcData.argNames)-1 { + link += "&" + } + } + buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a></br>", link, link)) + } + buf.WriteString("</body></html>") + w.Header().Set("Content-Type", "text/html") + w.WriteHeader(200) + w.Write(buf.Bytes()) +} diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_params.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_params.go new file mode 100644 index 00000000..acf5b4c8 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_params.go @@ -0,0 +1,89 @@ +package rpcserver + +import ( + "encoding/hex" + "fmt" + "net/http" + "regexp" + "strconv" +) + +var ( + // Parts of regular expressions + atom = "[A-Z0-9!#$%&'*+\\-/=?^_`{|}~]+" + dotAtom = atom + `(?:\.` + atom + `)*` + domain = `[A-Z0-9.-]+\.[A-Z]{2,4}` + + RE_HEX = regexp.MustCompile(`^(?i)[a-f0-9]+$`) + RE_EMAIL = regexp.MustCompile(`^(?i)(` + dotAtom + `)@(` + dotAtom + `)$`) + RE_ADDRESS = regexp.MustCompile(`^(?i)[a-z0-9]{25,34}$`) + RE_HOST = regexp.MustCompile(`^(?i)(` + domain + `)$`) + + //RE_ID12 = regexp.MustCompile(`^[a-zA-Z0-9]{12}$`) +) + +func GetParam(r *http.Request, param string) string { + s := r.URL.Query().Get(param) + if s == "" { + s = r.FormValue(param) + } + return s +} + +func GetParamByteSlice(r *http.Request, param string) ([]byte, error) { + s := GetParam(r, param) + return hex.DecodeString(s) +} + +func GetParamInt64(r *http.Request, param string) (int64, error) { + s := GetParam(r, param) + i, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return i, nil +} + +func GetParamInt32(r *http.Request, param string) (int32, error) { + s := GetParam(r, param) + i, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return int32(i), nil +} + +func GetParamUint64(r *http.Request, param string) (uint64, error) { + s := GetParam(r, param) + i, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return i, nil +} + +func GetParamUint(r *http.Request, param string) (uint, error) { + s := GetParam(r, param) + i, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return uint(i), nil +} + +func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) { + s := GetParam(r, param) + if !re.MatchString(s) { + return "", fmt.Errorf(param, "Did not match regular expression %v", re.String()) + } + return s, nil +} + +func GetParamFloat64(r *http.Request, param string) (float64, error) { + s := GetParam(r, param) + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return f, nil +} diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_server.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_server.go new file mode 100644 index 00000000..beec9bcc --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/http_server.go @@ -0,0 +1,123 @@ +// Commons for HTTP handling +package rpcserver + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "net/http" + "runtime/debug" + "time" + + "github.com/tendermint/go-alert" + . "github.com/tendermint/go-common" + . "github.com/tendermint/go-rpc/types" + //"github.com/tendermint/go-wire" +) + +func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, error) { + // listenAddr is `IP:PORT` or /path/to/socket + socketType := SocketType(listenAddr) + log.Notice(Fmt("Starting RPC HTTP server on %s socket %v", socketType, listenAddr)) + listener, err := net.Listen(socketType, listenAddr) + if err != nil { + return nil, fmt.Errorf("Failed to listen to %v: %v", listenAddr, err) + } + + go func() { + res := http.Serve( + listener, + RecoverAndLogHandler(handler), + ) + log.Crit("RPC HTTP server stopped", "result", res) + }() + return listener, nil +} + +func WriteRPCResponseHTTP(w http.ResponseWriter, res RPCResponse) { + // jsonBytes := wire.JSONBytesPretty(res) + jsonBytes, err := json.Marshal(res) + if err != nil { + panic(err) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + w.Write(jsonBytes) +} + +//----------------------------------------------------------------------------- + +// Wraps an HTTP handler, adding error logging. +// If the inner function panics, the outer function recovers, logs, sends an +// HTTP 500 error response. +func RecoverAndLogHandler(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Wrap the ResponseWriter to remember the status + rww := &ResponseWriterWrapper{-1, w} + begin := time.Now() + + // Common headers + origin := r.Header.Get("Origin") + rww.Header().Set("Access-Control-Allow-Origin", origin) + rww.Header().Set("Access-Control-Allow-Credentials", "true") + rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time") + rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix())) + + defer func() { + // Send a 500 error if a panic happens during a handler. + // Without this, Chrome & Firefox were retrying aborted ajax requests, + // at least to my localhost. + if e := recover(); e != nil { + + // If RPCResponse + if res, ok := e.(RPCResponse); ok { + WriteRPCResponseHTTP(rww, res) + } else { + // For the rest, + log.Error("Panic in RPC HTTP handler", "error", e, "stack", string(debug.Stack())) + rww.WriteHeader(http.StatusInternalServerError) + WriteRPCResponseHTTP(rww, NewRPCResponse("", nil, Fmt("Internal Server Error: %v", e))) + } + } + + // Finally, log. + durationMS := time.Since(begin).Nanoseconds() / 1000000 + if rww.Status == -1 { + rww.Status = 200 + } + log.Info("Served RPC HTTP response", + "method", r.Method, "url", r.URL, + "status", rww.Status, "duration", durationMS, + "remoteAddr", r.RemoteAddr, + ) + }() + + handler.ServeHTTP(rww, r) + }) +} + +// Remember the status for logging +type ResponseWriterWrapper struct { + Status int + http.ResponseWriter +} + +func (w *ResponseWriterWrapper) WriteHeader(status int) { + w.Status = status + w.ResponseWriter.WriteHeader(status) +} + +// implements http.Hijacker +func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return w.ResponseWriter.(http.Hijacker).Hijack() +} + +// Stick it as a deferred statement in gouroutines to prevent the program from crashing. +func Recover(daemonName string) { + if e := recover(); e != nil { + stack := string(debug.Stack()) + errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack) + alert.Alert(errorString) + } +} diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/log.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/log.go new file mode 100644 index 00000000..aab9721f --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/server/log.go @@ -0,0 +1,7 @@ +package rpcserver + +import ( + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" +) + +var log = log15.New("module", "rpcserver") diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/types/types.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/types/types.go new file mode 100644 index 00000000..47e8edeb --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/types/types.go @@ -0,0 +1,91 @@ +package rpctypes + +import ( + "encoding/json" + "strings" + + "github.com/tendermint/go-events" + "github.com/tendermint/go-wire" +) + +type RPCRequest struct { + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Method string `json:"method"` + Params []interface{} `json:"params"` +} + +func NewRPCRequest(id string, method string, params []interface{}) RPCRequest { + return RPCRequest{ + JSONRPC: "2.0", + ID: id, + Method: method, + Params: params, + } +} + +//---------------------------------------- + +/* +Result is a generic interface. +Applications should register type-bytes like so: + +var _ = wire.RegisterInterface( + struct{ Result }{}, + wire.ConcreteType{&ResultGenesis{}, ResultTypeGenesis}, + wire.ConcreteType{&ResultBlockchainInfo{}, ResultTypeBlockchainInfo}, + ... +) +*/ +type Result interface { +} + +//---------------------------------------- + +type RPCResponse struct { + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Result *json.RawMessage `json:"result"` + Error string `json:"error"` +} + +func NewRPCResponse(id string, res interface{}, err string) RPCResponse { + var raw *json.RawMessage + if res != nil { + rawMsg := json.RawMessage(wire.JSONBytes(res)) + raw = &rawMsg + } + return RPCResponse{ + JSONRPC: "2.0", + ID: id, + Result: raw, + Error: err, + } +} + +//---------------------------------------- + +// *wsConnection implements this interface. +type WSRPCConnection interface { + GetRemoteAddr() string + GetEventSwitch() *events.EventSwitch + WriteRPCResponse(resp RPCResponse) + TryWriteRPCResponse(resp RPCResponse) bool +} + +// websocket-only RPCFuncs take this as the first parameter. +type WSRPCContext struct { + Request RPCRequest + WSRPCConnection +} + +//---------------------------------------- +// sockets + +func SocketType(listenAddr string) string { + socketType := "unix" + if len(strings.Split(listenAddr, ":")) == 2 { + socketType = "tcp" + } + return socketType +} diff --git a/Godeps/_workspace/src/github.com/tendermint/go-rpc/version.go b/Godeps/_workspace/src/github.com/tendermint/go-rpc/version.go new file mode 100644 index 00000000..d0a0ee9c --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/go-rpc/version.go @@ -0,0 +1,7 @@ +package rpc + +const Maj = "0" +const Min = "5" // refactored out of tendermint/tendermint; RPCResponse.Result is RawJSON +const Fix = "0" + +const Version = Maj + "." + Min + "." + Fix diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go index 01d71466..5e546d34 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go @@ -96,7 +96,12 @@ func (memR *MempoolReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) { func (memR *MempoolReactor) ResetForBlockAndState(block *types.Block, state *sm.State) { ri := memR.Mempool.ResetForBlockAndState(block, state) for _, peer := range memR.Switch.Peers().List() { - peerMempoolCh := peer.Data.Get(types.PeerMempoolChKey).(chan ResetInfo) + peerMempoolChI := peer.Data.Get(types.PeerMempoolChKey) + peerMempoolCh, ok := peerMempoolChI.(chan ResetInfo) + if !ok { + // peer created before reset info established? + continue + } select { case peerMempoolCh <- ri: default: diff --git a/erisdb/serve.go b/erisdb/serve.go index f3b09024..d9c1c730 100644 --- a/erisdb/serve.go +++ b/erisdb/serve.go @@ -11,7 +11,7 @@ import ( ep "github.com/eris-ltd/eris-db/erisdb/pipe" "github.com/eris-ltd/eris-db/server" - "github.com/eris-ltd/mint-client/mintx/core" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/eris-ltd/mint-client/mintx/core" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" -- GitLab