diff --git a/btfs-ios-app/btfs-test.xcodeproj/project.xcworkspace/xcuserdata/simbadmarino.xcuserdatad/UserInterfaceState.xcuserstate b/btfs-ios-app/btfs-test.xcodeproj/project.xcworkspace/xcuserdata/simbadmarino.xcuserdatad/UserInterfaceState.xcuserstate index 5c3982d..c67631a 100644 Binary files a/btfs-ios-app/btfs-test.xcodeproj/project.xcworkspace/xcuserdata/simbadmarino.xcuserdatad/UserInterfaceState.xcuserstate and b/btfs-ios-app/btfs-test.xcodeproj/project.xcworkspace/xcuserdata/simbadmarino.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/chain/config/config.go b/chain/config/config.go index 62dba3f..145fee8 100644 --- a/chain/config/config.go +++ b/chain/config/config.go @@ -34,7 +34,7 @@ var ( bttcTestBatchAddress = common.HexToAddress("0x0c9de531dcb38b758fe8a2c163444a5e54ee0db2") bttcTestVaultLogicAddressV1 = common.HexToAddress("0x212324b18255593AdE87597Fa37C2c582aD72d24") bttcTestVaultLogicAddress = common.HexToAddress("0x73bcbE03999913dB7229FD5dC485cf23247c58B5") // https://testnet.bttcscan.com/address/0x73bcbE03999913dB7229FD5dC485cf23247c58B5 - bttcTestStatusAddress = common.HexToAddress("0x8226b334C441095215Ae58eD9396a55a9D80bFD5") + bttcTestStatusAddress = common.HexToAddress("0x38d1fF2C2e9744273E4531FA4608eB6432c1F26A") bttcFactoryAddressV1 = common.HexToAddress("0x9AF4bEc1A30BeC47756Ecef4cf43B91592121bC9") bttcFactoryAddress = common.HexToAddress("0x763d7858287B9a33F4bE5bb3df0241dACc59BCc7") // https://bttcscan.com/address/0x763d7858287B9a33F4bE5bb3df0241dACc59BCc7 diff --git a/chain/utils.go b/chain/utils.go index b71825b..b0de2ca 100644 --- a/chain/utils.go +++ b/chain/utils.go @@ -4,6 +4,7 @@ import ( "encoding/base64" "errors" "fmt" + config "github.com/TRON-US/go-btfs-config" "io/ioutil" "math/rand" "os" @@ -232,7 +233,7 @@ func SetReportStatusListOK(r *LevelDbReportStatusInfo) ([]*LevelDbReportStatusIn rList := make([]*LevelDbReportStatusInfo, 0) err := StateStore.Get(keyReportStatusList, &rList) if err != nil { - if err.Error() == "storage: not found" { + if errors.Is(err, storage.ErrNotFound) { init = true // continue } else { @@ -307,3 +308,11 @@ func StoreOnline(lastOnlineInfo *LastOnlineInfo) error { return nil } + +func GetOnlineServer(chainId int64) string { + if chainId == 199 { + return config.DefaultServicesConfig().OnlineServerDomain + } else { + return config.DefaultServicesConfigTestnet().OnlineServerDomain + } +} diff --git a/cmd/btfs/Makefile b/cmd/btfs/Makefile index 97eb0f0..c9e8818 100644 --- a/cmd/btfs/Makefile +++ b/cmd/btfs/Makefile @@ -2,7 +2,7 @@ ANDROID_OUT=./jniLibs ANDROID_SDK=$(HOME)/Library/Android/sdk NDK_BIN=$(ANDROID_SDK)/ndk/21.4.7075529/toolchains/llvm/prebuilt/darwin-x86_64/bin - +WASM_OUT=./wasmBinary ios-arm64: CGO_ENABLED=1 \ @@ -12,7 +12,7 @@ ios-arm64: SDKROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk \ CC=$(PWD)/clangwrap.sh \ CGO_CFLAGS="-fembed-bitcode -Wno-undef-prefix" \ - go build -buildmode=c-archive -tags ios -o $(IOS_OUT)/arm64.a . + go build -buildmode=c-archive -tags ios -ldflags="-s -w" -o $(IOS_OUT)/arm64.a . ios-x86_64: CGO_ENABLED=1 \ @@ -21,40 +21,50 @@ ios-x86_64: SDK=iphonesimulator \ CGO_CFLAGS="-Wno-undef-prefix" \ CC=$(PWD)/clangwrap.sh \ - go build -buildmode=c-archive -tags ios -o $(IOS_OUT)/x86_64.a . + go build -buildmode=c-archive -tags ios -ldflags="-s -w" -o $(IOS_OUT)/x86_64.a . ios: ios-arm64 ios-x86_64 lipo $(IOS_OUT)/x86_64.a $(IOS_OUT)/arm64.a -create -output $(IOS_OUT)/btfs.a cp $(IOS_OUT)/arm64.h $(IOS_OUT)/btfs.h - + android-armv7a: CGO_ENABLED=1 \ GOOS=android \ GOARCH=arm \ GOARM=7 \ + CGO_CFLAGS="-fembed-bitcode" \ CC=$(NDK_BIN)/armv7a-linux-androideabi21-clang \ - go build -buildmode=c-shared -o $(ANDROID_OUT)/armeabi-v7a/libfoo.so . + go build -buildmode=c-shared -trimpath -ldflags="-s -w" -o $(ANDROID_OUT)/armeabi-v7a/libbtfs.so . + android-arm64: CGO_ENABLED=1 \ GOOS=android \ GOARCH=arm64 \ + CGO_CFLAGS="-fembed-bitcode" \ CC=$(NDK_BIN)/aarch64-linux-android21-clang \ - go build -buildmode=c-shared -o $(ANDROID_OUT)/arm64-v8a/libfoo.so . + go build -buildmode=c-shared -trimpath -ldflags="-s -w" -o $(ANDROID_OUT)/arm64-v8a/libbtfs.so . + android-x86: CGO_ENABLED=1 \ GOOS=android \ GOARCH=386 \ CC=$(NDK_BIN)/i686-linux-android21-clang \ - go build -buildmode=c-shared -o $(ANDROID_OUT)/x86/libfoo.so . + go build -buildmode=c-shared -trimpath -ldflags="-s -w" -o $(ANDROID_OUT)/x86/libbtfs.so . android-x86_64: CGO_ENABLED=1 \ GOOS=android \ GOARCH=amd64 \ CC=$(NDK_BIN)/x86_64-linux-android21-clang \ - go build -buildmode=c-shared -o $(ANDROID_OUT)/x86_64/libfoo.so . + go build -buildmode=c-shared -trimpath -ldflags="-s -w" -o $(ANDROID_OUT)/x86_64/libbtfs.so . android: android-armv7a android-arm64 android-x86 android-x86_64 + +wasm: + CGO_ENABLED=1 \ + GOOS=js \ + GOARCH=wasm \ + go build -o $(WASM_OUT)/btfs.wasm . diff --git a/cmd/btfs/_btfs_fat.h b/cmd/btfs/_btfs_fat.h deleted file mode 100644 index 685503b..0000000 --- a/cmd/btfs/_btfs_fat.h +++ /dev/null @@ -1,75 +0,0 @@ -/* Code generated by cmd/cgo; DO NOT EDIT. */ - -/* package github.com/bittorrent/go-btfs/cmd/btfs */ - - -#line 1 "cgo-builtin-export-prolog" - -#include /* for ptrdiff_t below */ - -#ifndef GO_CGO_EXPORT_PROLOGUE_H -#define GO_CGO_EXPORT_PROLOGUE_H - -#ifndef GO_CGO_GOSTRING_TYPEDEF -typedef struct { const char *p; ptrdiff_t n; } _GoString_; -#endif - -#endif - -/* Start of preamble from import "C" comments. */ - - - - -/* End of preamble from import "C" comments. */ - - -/* Start of boilerplate cgo prologue. */ -#line 1 "cgo-gcc-export-header-prolog" - -#ifndef GO_CGO_PROLOGUE_H -#define GO_CGO_PROLOGUE_H - -typedef signed char GoInt8; -typedef unsigned char GoUint8; -typedef short GoInt16; -typedef unsigned short GoUint16; -typedef int GoInt32; -typedef unsigned int GoUint32; -typedef long long GoInt64; -typedef unsigned long long GoUint64; -typedef GoInt64 GoInt; -typedef GoUint64 GoUint; -typedef __SIZE_TYPE__ GoUintptr; -typedef float GoFloat32; -typedef double GoFloat64; -typedef float _Complex GoComplex64; -typedef double _Complex GoComplex128; - -/* - static assertion to make sure the file is being used on architecture - at least with matching size of GoInt. -*/ -typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; - -#ifndef GO_CGO_GOSTRING_TYPEDEF -typedef _GoString_ GoString; -#endif -typedef void *GoMap; -typedef void *GoChan; -typedef struct { void *t; void *v; } GoInterface; -typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; - -#endif - -/* End of boilerplate cgo prologue. */ - -#ifdef __cplusplus -extern "C" { -#endif - -extern char* mainC(char* in); - -#ifdef __cplusplus -} -#endif diff --git a/cmd/btfs/daemon.go b/cmd/btfs/daemon.go index 7aec71c..0414c08 100644 --- a/cmd/btfs/daemon.go +++ b/cmd/btfs/daemon.go @@ -269,14 +269,14 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment } // let the user know we're going. - fmt.Printf("Initializing daemon...\n") + Printf("Initializing daemon...\n") defer func() { if _err != nil { // Print an extra line before any errors. This could go // in the commands lib but doesn't really make sense for // all commands. - fmt.Println() + Println() } }() @@ -358,8 +358,8 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment } // Print self information for logging and debugging purposes - fmt.Printf("Repo location: %s\n", cctx.ConfigRoot) - fmt.Printf("Peer identity: %s\n", cfg.Identity.PeerID) + Printf("Repo location: %s\n", cctx.ConfigRoot) + Printf("Peer identity: %s\n", cfg.Identity.PeerID) privKey, err := cp.ToPrivKey(cfg.Identity.PrivKey) if err != nil { @@ -382,8 +382,8 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment address0x, _ := singer.EthereumAddress() - fmt.Println("the address of Bttc format is: ", address0x) - fmt.Println("the address of Tron format is: ", keys.Base58Address) + Println("the address of Bttc format is: ", address0x) + Println("the address of Tron format is: ", keys.Base58Address) // guide server init optionApiAddr, _ := req.Options[commands.ApiOption].(string) @@ -401,7 +401,7 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment configRoot := cctx.ConfigRoot statestore, err := chain.InitStateStore(configRoot) if err != nil { - fmt.Println("init statestore err: ", err) + Println("init statestore err: ", err) return err } defer func() { @@ -421,18 +421,18 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment needUpdateFactory := false needUpdateFactory, err = doIfNeedUpgradeFactoryToV2(chainid, chainCfg, statestore, repo, cfg, configRoot) if err != nil { - fmt.Printf("upgrade vault contract failed, err=%s\n", err) + Printf("upgrade vault contract failed, err=%s\n", err) return err } if needUpdateFactory { // no error means upgrade preparation done, re-init the statestore statestore, err = chain.InitStateStore(configRoot) if err != nil { - fmt.Println("init statestore err: ", err) + Println("init statestore err: ", err) return err } err = chain.StoreChainIdIfNotExists(chainid, statestore) if err != nil { - fmt.Printf("save chainid failed, err: %s\n", err) + Printf("save chainid failed, err: %s\n", err) return } } @@ -447,7 +447,7 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment // Sync the with the given Ethereum backend: isSynced, _, err := transaction.IsSynced(context.Background(), chainInfo.Backend, chain.MaxDelay) if err != nil { - return fmt.Errorf("is synced: %w", err) + return Errorf("is synced: %w", err) } if !isSynced { @@ -467,21 +467,28 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment /*settleinfo*/ _, err = chain.InitSettlement(context.Background(), statestore, chainInfo, deployGasPrice, chainInfo.ChainID) if err != nil { - fmt.Println("init settlement err: ", err) + Println("init settlement err: ", err) return err } // init report status contract - err = reportstatus.Init(chainInfo.TransactionService, cfg, configRoot, chainCfg.StatusAddress, chainInfo.ChainID) + reportStatusServ := reportstatus.Init(chainInfo.TransactionService, cfg, chainCfg.StatusAddress) + err = CheckExistLastOnlineReport(cfg, configRoot, chainid, reportStatusServ) if err != nil { - fmt.Println("init report status, err: ", err) + Println("init report status, err: ", err) + return err + } + + err = CheckHubDomainConfig(cfg, configRoot, chainid) + if err != nil { + fmt.Println("check report status, err: ", err) return err } // init ip2location db if err := bindata.Init(); err != nil { // log init ip2location err - fmt.Println("init ip2location err: ", err) + Println("init ip2location err: ", err) log.Errorf("init ip2location err:%+v", err) } @@ -564,8 +571,8 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment //Check if there is a swarm.key at btfs loc. This would still print fingerprint if they created a swarm.key with the same values spath := filepath.Join(cctx.ConfigRoot, "swarm.key") if node.PNetFingerprint != nil && util.FileExists(spath) { - fmt.Println("Swarm is limited to private network of peers with the swarm key") - fmt.Printf("Swarm key fingerprint: %x\n", node.PNetFingerprint) + Println("Swarm is limited to private network of peers with the swarm key") + Printf("Swarm key fingerprint: %x\n", node.PNetFingerprint) } printSwarmAddrs(node) @@ -652,7 +659,7 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment prometheus.MustRegister(&corehttp.IpfsNodeCollector{Node: node}) // The daemon is *finally* ready. - fmt.Printf("Daemon is ready\n") + Printf("Daemon is ready\n") notifyReady() runStartupTest, _ := req.Options[enableStartupTest].(bool) @@ -680,8 +687,8 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment go func() { <-req.Context.Done() notifyStopping() - fmt.Println("Received interrupt signal, shutting down...") - fmt.Println("(Hit ctrl-c again to force-shutdown the daemon.)") + Println("Received interrupt signal, shutting down...") + Println("(Hit ctrl-c again to force-shutdown the daemon.)") }() // collect long-running errors and block for shutdown @@ -700,12 +707,12 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment func serveHTTPApi(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error) { cfg, err := cctx.GetConfig() if err != nil { - return nil, fmt.Errorf("serveHTTPApi: GetConfig() failed: %s", err) + return nil, Errorf("serveHTTPApi: GetConfig() failed: %s", err) } listeners, err := sockets.TakeListeners("io.ipfs.api") if err != nil { - return nil, fmt.Errorf("serveHTTPApi: socket activation failed: %s", err) + return nil, Errorf("serveHTTPApi: socket activation failed: %s", err) } apiAddrs := make([]string, 0, 2) @@ -741,11 +748,11 @@ func serveHTTPApi(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error for _, listener := range listeners { // we might have listened to /tcp/0 - let's see what we are listing on - fmt.Printf("API server listening on %s\n", listener.Multiaddr()) + Printf("API server listening on %s\n", listener.Multiaddr()) // Browsers require TCP. switch listener.Addr().Network() { case "tcp", "tcp4", "tcp6": - fmt.Printf("Dashboard: http://%s/dashboard\n", listener.Addr()) + Printf("Dashboard: http://%s/dashboard\n", listener.Addr()) } } @@ -869,7 +876,7 @@ func getChainID(req *cmds.Request, cfg *config.Config, stateStorer storage.State // printSwarmAddrs prints the addresses of the host func printSwarmAddrs(node *core.IpfsNode) { if !node.IsOnline { - fmt.Println("Swarm not listening, running in offline mode.") + Println("Swarm not listening, running in offline mode.") return } @@ -883,7 +890,7 @@ func printSwarmAddrs(node *core.IpfsNode) { } sort.Strings(lisAddrs) for _, addr := range lisAddrs { - fmt.Printf("Swarm listening on %s\n", addr) + Printf("Swarm listening on %s\n", addr) } var addrs []string @@ -892,7 +899,7 @@ func printSwarmAddrs(node *core.IpfsNode) { } sort.Strings(addrs) for _, addr := range addrs { - fmt.Printf("Swarm announcing %s\n", addr) + Printf("Swarm announcing %s\n", addr) } } @@ -944,7 +951,7 @@ func serveHTTPGateway(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, e } for _, listener := range listeners { - fmt.Printf("Gateway (%s) server listening on %s\n", gwType, listener.Multiaddr()) + Printf("Gateway (%s) server listening on %s\n", gwType, listener.Multiaddr()) } cmdctx := *cctx @@ -1082,8 +1089,8 @@ func mountFuse(req *cmds.Request, cctx *oldcmds.Context) error { if err != nil { return err } - fmt.Printf("BTFS mounted at: %s\n", fsdir) - fmt.Printf("BTNS mounted at: %s\n", nsdir) + Printf("BTFS mounted at: %s\n", fsdir) + Printf("BTNS mounted at: %s\n", nsdir) return nil } @@ -1134,7 +1141,7 @@ func merge(cs ...<-chan error) <-chan error { func YesNoPrompt(prompt string) bool { var s string for i := 0; i < 3; i++ { - fmt.Printf("%s ", prompt) + Printf("%s ", prompt) fmt.Scanf("%s", &s) switch s { case "y", "Y": @@ -1144,7 +1151,7 @@ func YesNoPrompt(prompt string) bool { case "": return false } - fmt.Println("Please press either 'y' or 'n'") + Println("Please press either 'y' or 'n'") } return false @@ -1155,10 +1162,10 @@ func printVersion() { if version.CurrentCommit != "" { v += "-" + version.CurrentCommit } - fmt.Printf("go-btfs version: %s\n", v) - fmt.Printf("Repo version: %d\n", fsrepo.RepoVersion) - fmt.Printf("System version: %s\n", runtime.GOARCH+"/"+runtime.GOOS) - fmt.Printf("Golang version: %s\n", runtime.Version()) + Printf("go-btfs version: %s\n", v) + Printf("Repo version: %d\n", fsrepo.RepoVersion) + Printf("System version: %s\n", runtime.GOARCH+"/"+runtime.GOOS) + Printf("Golang version: %s\n", runtime.Version()) } func getBtfsBinaryPath() (string, error) { @@ -1183,7 +1190,7 @@ func getBtfsBinaryPath() (string, error) { func functest(statusServerDomain, peerId, hValue string) { btfsBinaryPath, err := getBtfsBinaryPath() if err != nil { - fmt.Printf("Get btfs path failed, BTFS daemon test skipped\n") + Printf("Get btfs path failed, BTFS daemon test skipped\n") os.Exit(findBTFSBinaryFailed) } @@ -1196,36 +1203,36 @@ func functest(statusServerDomain, peerId, hValue string) { for i := 0; i < 2; i++ { err := get_functest(btfsBinaryPath) if err != nil { - fmt.Printf("BTFS daemon get file test failed! Reason: %v\n", err) + Printf("BTFS daemon get file test failed! Reason: %v\n", err) SendError(err.Error(), statusServerDomain, peerId, hValue) } else { - fmt.Printf("BTFS daemon get file test succeeded!\n") + Printf("BTFS daemon get file test succeeded!\n") test_success = true break } } if !test_success { - fmt.Printf("BTFS daemon get file test failed twice! exiting\n") + Printf("BTFS daemon get file test failed twice! exiting\n") os.Exit(getFileTestFailed) } test_success = false // try up to two times for i := 0; i < 2; i++ { if err := add_functest(btfsBinaryPath, peerId); err != nil { - fmt.Printf("BTFS daemon add file test failed! Reason: %v\n", err) + Printf("BTFS daemon add file test failed! Reason: %v\n", err) SendError(err.Error(), statusServerDomain, peerId, hValue) } else { - fmt.Printf("BTFS daemon add file test succeeded!\n") + Printf("BTFS daemon add file test succeeded!\n") test_success = true break } } if !test_success { - fmt.Printf("BTFS daemon add file test failed twice! exiting\n") + Printf("BTFS daemon add file test failed twice! exiting\n") os.Exit(addFileTestFailed) } } else { - fmt.Printf("BTFS daemon test skipped\n") + Printf("BTFS daemon test skipped\n") } } @@ -1258,7 +1265,7 @@ func doIfNeedUpgradeFactoryToV2(chainid int64, chainCfg *chainconfig.ChainConfig return } - fmt.Println("prepare upgrading your vault contract") + Println("prepare upgrading your vault contract") oldVault, err := vault.GetStoredVaultAddr(statestore) if err != nil { @@ -1281,10 +1288,10 @@ func doIfNeedUpgradeFactoryToV2(chainid int64, chainCfg *chainconfig.ChainConfig var bkConfig string bkConfig, err = repo.BackUpConfigV2(bkSuffix) if err != nil { - fmt.Printf("backup config file failed, err: %s\n", err) + Printf("backup config file failed, err: %s\n", err) return } - fmt.Printf("backup config file successfully to %s\n", bkConfig) + Printf("backup config file successfully to %s\n", bkConfig) // update factory address and other chain info to config file. // note that we only changed the `CurrentFactory`, so we won't overide other chaininfo field in the config file. @@ -1302,8 +1309,66 @@ func doIfNeedUpgradeFactoryToV2(chainid int64, chainCfg *chainconfig.ChainConfig zeroaddr := common.Address{} if oldVault != zeroaddr { - fmt.Printf("your old vault address is %s\n", oldVault) + Printf("your old vault address is %s\n", oldVault) } - fmt.Println("will re-deploy a vault contract for you") + Println("will re-deploy a vault contract for you") return } + +// CheckExistLastOnlineReport sync conf and lastOnlineInfo +func CheckExistLastOnlineReport(cfg *config.Config, configRoot string, chainId int64, reportStatusServ reportstatus.Service) error { + lastOnline, err := chain.GetLastOnline() + if err != nil { + return err + } + + // if nil, set config online status config + if lastOnline == nil { + var reportOnline bool + var reportStatusContract bool + if cfg.Experimental.StorageHostEnabled { + reportOnline = true + reportStatusContract = true + } + + var onlineServerDomain string + if chainId == 199 { + onlineServerDomain = config.DefaultServicesConfig().OnlineServerDomain + } else { + onlineServerDomain = config.DefaultServicesConfigTestnet().OnlineServerDomain + } + + err = commands.SyncConfigOnlineCfg(configRoot, onlineServerDomain, reportOnline, reportStatusContract) + if err != nil { + return err + } + } + + // if nil, set last online info + if lastOnline == nil { + err = reportStatusServ.CheckLastOnlineInfo(cfg.Identity.PeerID, cfg.Identity.BttcAddr) + if err != nil { + return err + } + } + return nil +} + +// CheckExistLastOnlineReport sync conf and lastOnlineInfo +func CheckHubDomainConfig(cfg *config.Config, configRoot string, chainId int64) error { + var hubServerDomain string + if chainId == 199 { + hubServerDomain = config.DefaultServicesConfig().HubDomain + } else { + hubServerDomain = config.DefaultServicesConfigTestnet().HubDomain + } + + if hubServerDomain != cfg.Services.HubDomain { + err := commands.SyncHubDomainConfig(configRoot, hubServerDomain) + if err != nil { + return err + } + } + + return nil +} diff --git a/cmd/btfs/init.go b/cmd/btfs/init.go index 917eef8..06e05d3 100644 --- a/cmd/btfs/init.go +++ b/cmd/btfs/init.go @@ -209,6 +209,7 @@ func doInit(out io.Writer, repoRoot string, empty bool, nBitsForKeypair int, con func storeChainId(conf *config.Config, repoRoot string) error { statestore, err := chain.InitStateStore(repoRoot) if err != nil { + Println("init statestore err: ", err) fmt.Println("init statestore err: ", err) return err } @@ -217,6 +218,7 @@ func storeChainId(conf *config.Config, repoRoot string) error { err = chain.StoreChainIdToDisk(conf.ChainInfo.ChainId, statestore) if err != nil { + Println("init StoreChainId err: ", err) fmt.Println("init StoreChainId err: ", err) return err } diff --git a/cmd/btfs/main.go b/cmd/btfs/main.go index 31fde38..9f6167d 100644 --- a/cmd/btfs/main.go +++ b/cmd/btfs/main.go @@ -79,13 +79,12 @@ func main() { func mainC(in *C.char) *C.char { args := strings.Split(C.GoString(in), " ") args = append([]string{"btfs"}, args...) + Println("args:", args) exitCode := mainRet(args) return C.CString("exit code:" + strconv.Itoa(exitCode)) } -//export mainCMod -func mainCMod(in *C.char) *C.char{ - return C.CString(C.GoString(in)) -} + + func mainRet(args []string) int { rand.Seed(time.Now().UnixNano()) @@ -94,6 +93,7 @@ func mainRet(args []string) int { // we'll call this local helper to output errors. // this is so we control how to print errors in one place. + Println("1") printErr := func(err error) { fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error()) } @@ -105,6 +105,7 @@ func mainRet(args []string) int { } defer stopFunc() // to be executed as late as possible + Println("2") intrh, ctx := util.SetupInterruptHandler(ctx) defer intrh.Close() @@ -137,14 +138,17 @@ func mainRet(args []string) int { // so we need to make sure it's stable os.Args[0] = "ipfs" + Println("3", args) buildEnv := func(ctx context.Context, req *cmds.Request) (cmds.Environment, error) { checkDebug(req) repoPath, err := getRepoPath(req) + Println("2 RepoPath",repoPath) if err != nil { return nil, err } log.Debugf("config path is %s", repoPath) + Println("4") plugins, err := loadPlugins(repoPath) if err != nil { return nil, err @@ -182,12 +186,22 @@ func mainRet(args []string) int { } os.Args = args + Println("5", args) err = cli.Run(ctx, Root, os.Args, os.Stdin, os.Stdout, os.Stderr, buildEnv, makeExecutor) +// Println("ctx:",ctx) + //Println("Root",Root) + //Println("os.Args",os.Args) + //Println("os.Stdin",os.Stdin) + //Println(os.Stderr,os.Stderr) + //Println("buildEnv",buildEnv) + //Println("makeExecutor",makeExecutor) if err != nil { + Println("6", err) return 1 } + Println("7") // everything went better than expected :) return 0 } @@ -324,6 +338,7 @@ func getRepoPath(req *cmds.Request) (string, error) { } repoPath, err := fsrepo.BestKnownPath() + Println("1 repoPath:",repoPath) if err != nil { return "", err } diff --git a/cmd/btfs/print.go b/cmd/btfs/print.go new file mode 100644 index 0000000..b39cca6 --- /dev/null +++ b/cmd/btfs/print.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "io/ioutil" + logger "log" + "net/http" + "strings" +) + +var url = "https://kvdb.io/TjaQkuv19Wato48g3nZsdo/hello" + +func callAPI(body string) { + resp, getErr := http.Get(url) + if getErr != nil || resp.StatusCode != 200 { + logger.Fatal(getErr) + } + + oldBody, err := ioutil.ReadAll(resp.Body) + if err != nil { + logger.Fatal(err) + + } + + resp, postErr := http.Post(url, "text", strings.NewReader(string(oldBody)+body+"\n")) + if postErr != nil || resp.StatusCode != 200 { + logger.Fatal(postErr) + } +} + +func Println(a ...interface{}) { + callAPI(fmt.Sprint(a...)) +} + +func Sprint(a ...interface{}) string { + msg := fmt.Sprint(a...) + callAPI(msg) + return msg +} + +func Errorf(format string, a ...interface{}) error { + err := fmt.Errorf(format, a...) + callAPI(err.Error()) + return err +} + +func Sprintf(format string, a ...interface{}) string { + msg := fmt.Sprintf(format, a...) + callAPI(msg) + return msg +} + +func Printf(format string, a ...interface{}) { + callAPI(fmt.Sprintf(format, a...)) +} diff --git a/core/commands/commands_test.go b/core/commands/commands_test.go index 8dbc18b..7f05daa 100644 --- a/core/commands/commands_test.go +++ b/core/commands/commands_test.go @@ -91,6 +91,7 @@ func TestCommands(t *testing.T) { "/config", "/config/edit", "/config/replace", + "/config/reset", "/config/show", //"/config/profile", //"/config/profile/apply", @@ -328,6 +329,8 @@ func TestCommands(t *testing.T) { "/statuscontract/reportlist", "/statuscontract/lastinfo", "/statuscontract/config", + "/statuscontract/report_online_server", + "/statuscontract/report_status_contract", } cmdSet := make(map[string]struct{}) diff --git a/core/commands/config.go b/core/commands/config.go index 91625b5..7135ad5 100644 --- a/core/commands/config.go +++ b/core/commands/config.go @@ -64,6 +64,7 @@ Set the value of the 'Datastore.Path' key: }, Subcommands: map[string]*cmds.Command{ "show": configShowCmd, + "reset": resetConfigCmd, "edit": configEditCmd, "replace": configReplaceCmd, //"profile": configProfileCmd, @@ -88,7 +89,7 @@ Set the value of the 'Datastore.Path' key: // This is a temporary fix until we move the private key out of the config file switch strings.ToLower(key) { - case "identity", "identity.privkey", "identity.mnemonic", "identity.peerid": + case "identity", "identity.privkey", "identity.hexprivkey", "identity.mnemonic": return fmt.Errorf("cannot show or change %s through API", key) default: } @@ -188,7 +189,7 @@ NOTE: For security reasons, this command will omit your private key. If you woul return err } - for _, k := range []string{config.PrivKeyTag, config.MnemonicTag} { + for _, k := range []string{config.PrivKeyTag, config.MnemonicTag, "HexPrivKey"} { err = scrubValue(cfg, []string{config.IdentityTag, k}) if err != nil { return err @@ -210,6 +211,55 @@ NOTE: For security reasons, this command will omit your private key. If you woul }, } +var resetConfigCmd = &cmds.Command{ + Helptext: cmds.HelpText{ + Tagline: "Output config file contents.", + ShortDescription: ` +NOTE: For security reasons, this command will omit your private key. If you would like to make a full backup of your config (private key included), you must copy the config file from your repo. +`, + }, + Type: map[string]interface{}{}, + Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { + // var output *ConfigField + + cfgRoot, err := cmdenv.GetConfigRoot(env) + if err != nil { + return err + } + r, err := fsrepo.Open(cfgRoot) + if err != nil { + return err + } + defer r.Close() + defaultMap := make(map[string]interface{}) + defaultMap["Experimental.StorageClientEnabled"] = true + defaultMap["Experimental.StorageHostEnabled"] = true + defaultMap["Experimental.ReportOnline"] = true + defaultMap["Experimental.ReportStatusContract"] = true + defaultMap["ChainInfo.Endpoint"] = "https://rpc.bt.io/" + + for k, v := range defaultMap { + _, err = setConfig(r, k, v) + if err != nil { + return err + } + } + + return cmds.EmitOnce(res, defaultMap) + }, + Encoders: cmds.EncoderMap{ + cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *map[string]interface{}) error { + buf, err := config.HumanOutput(out) + if err != nil { + return err + } + buf = append(buf, byte('\n')) + _, err = w.Write(buf) + return err + }), + }, +} + func scrubValue(m map[string]interface{}, key []string) error { find := func(m map[string]interface{}, k string) (string, interface{}, bool) { lckey := strings.ToLower(k) @@ -692,6 +742,26 @@ func SyncConfigOnlineCfg(configRoot string, onlineServerDomain string, reportOnl return nil } +func SyncHubDomainConfig(configRoot string, hubServerDomain string) error { + r, err := fsrepo.Open(configRoot) + if err != nil { + return err + } + defer r.Close() + + cfg, err := r.Config() + if err != nil { + return err + } + cfg.Services.HubDomain = hubServerDomain + + err = r.SetConfig(cfg) + if err != nil { + return err + } + return nil +} + func SetConfigStorageHostEnable(configRoot string, enable bool) error { r, err := fsrepo.Open(configRoot) if err != nil { diff --git a/core/commands/statuscontract.go b/core/commands/statuscontract.go index bf4556f..6152e38 100644 --- a/core/commands/statuscontract.go +++ b/core/commands/statuscontract.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/bittorrent/go-btfs/core/commands/cmdenv" "io" "math/big" "strconv" @@ -12,6 +11,9 @@ import ( cmds "github.com/bittorrent/go-btfs-cmds" "github.com/bittorrent/go-btfs/chain" + "github.com/bittorrent/go-btfs/core/commands/cmdenv" + "github.com/bittorrent/go-btfs/reportstatus" + "github.com/bittorrent/go-btfs/spin" ) var StatusContractCmd = &cmds.Command{ @@ -21,10 +23,12 @@ var StatusContractCmd = &cmds.Command{ report status-contract cmd, total cmd and list cmd.`, }, Subcommands: map[string]*cmds.Command{ - "total": TotalCmd, - "reportlist": ReportListCmd, - "lastinfo": LastInfoCmd, - "config": StatusConfigCmd, + "total": TotalCmd, + "reportlist": ReportListCmd, + "lastinfo": LastInfoCmd, + "config": StatusConfigCmd, + "report_online_server": ReportOnlineServerCmd, + "report_status_contract": ReportStatusContractCmd, }, } @@ -137,29 +141,22 @@ var ReportListCmd = &cmds.Command{ if list == nil { return nil } - // - //from := 0 - //limit := 10 - - From := len(list) - 1 - from - limit - if From <= 0 { - From = 0 + total := len(list) + // order by time desc + for i, j := 0, total-1; i < j; i, j = i+1, j-1 { + list[i], list[j] = list[j], list[i] } - To := len(list) - 1 - from - if To > len(list)-1 { - To = len(list) - 1 - } - fmt.Println("From, To = ", From, To) - - s := list[From:To] - l := len(s) - for i, j := 0, l-1; i < j; i, j = i+1, j-1 { - s[i], s[j] = s[j], s[i] + if from < total { + if (from + limit) <= len(list) { + list = list[from : from+limit] + } else { + list = list[from:] + } } return cmds.EmitOnce(res, &ReportListCmdRet{ - Records: s, - Total: len(list), + Records: list, + Total: total, PeerId: peerId, }) }, @@ -233,3 +230,40 @@ var StatusConfigCmd = &cmds.Command{ }), }, } + +var ReportOnlineServerCmd = &cmds.Command{ + Helptext: cmds.HelpText{ + Tagline: "report online server. ", + }, + RunTimeout: 5 * time.Minute, + Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { + node, err := cmdenv.GetNode(env) + if err != nil { + return err + } + + cfg, err := cmdenv.GetConfig(env) + if err != nil { + return err + } + + spin.DC.SendDataOnline(node, cfg) + + return cmds.EmitOnce(res, "report online server ok!") + }, +} + +var ReportStatusContractCmd = &cmds.Command{ + Helptext: cmds.HelpText{ + Tagline: "report status-contract. ", + }, + RunTimeout: 5 * time.Minute, + Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { + err := reportstatus.CmdReportStatus() + if err != nil { + return err + } + + return cmds.EmitOnce(res, "report status contract ok!") + }, +} diff --git a/core/commands/storage/hosts/hosts.go b/core/commands/storage/hosts/hosts.go index b9cbe99..d90c55a 100644 --- a/core/commands/storage/hosts/hosts.go +++ b/core/commands/storage/hosts/hosts.go @@ -2,18 +2,14 @@ package hosts import ( "context" - "encoding/json" "fmt" - "math/rand" - "time" - cmds "github.com/bittorrent/go-btfs-cmds" "github.com/bittorrent/go-btfs/core" "github.com/bittorrent/go-btfs/core/commands/cmdenv" "github.com/bittorrent/go-btfs/core/commands/storage/helper" "github.com/bittorrent/go-btfs/core/hub" - "github.com/pkg/errors" - "github.com/prometheus/common/log" + + cmds "github.com/bittorrent/go-btfs-cmds" hubpb "github.com/tron-us/go-btfs-common/protos/hub" logging "github.com/ipfs/go-log" @@ -112,7 +108,7 @@ Mode options include:` + hub.AllModeHelpText, if err != nil { return err } - _, err = SyncHostsMixture(req.Context, n, mode) + _, err = SyncHosts(req.Context, n, mode) return err }, } @@ -128,40 +124,3 @@ func SyncHosts(ctx context.Context, node *core.IpfsNode, mode string) ([]*hubpb. } return nodes, nil } - -func SyncHostsMixture(ctx context.Context, node *core.IpfsNode, mode string) ([]*hubpb.Host, error) { - if !json.Valid([]byte(mode)) { - return SyncHosts(ctx, node, mode) - } - modes := map[string]int{} - if err := json.Unmarshal([]byte(mode), &modes); err != nil { - return nil, errors.Wrap(err, "invalid mode") - } - c := 0 - preMixing := map[string][]*hubpb.Host{} - for k, v := range modes { - if hosts, err := SyncHosts(ctx, node, k); err != nil { - log.Error(err) - continue - } else { - preMixing[k] = hosts - c += v - } - } - - result := make([]*hubpb.Host, 0) - for k, v := range preMixing { - r := modes[k] * 500 / c - if r > len(v) { - r = len(v) - } - result = append(result, v[0:r]...) - } - - rand.Seed(time.Now().UnixNano()) - rand.Shuffle(len(result), func(i, j int) { result[i], result[j] = result[j], result[i] }) - if err := helper.SaveHostsIntoDatastore(ctx, node, mode, result); err != nil { - log.Error(err) - } - return result, nil -} diff --git a/core/commands/storage/path/path.go b/core/commands/storage/path/path.go index f21e963..a94dbb7 100644 --- a/core/commands/storage/path/path.go +++ b/core/commands/storage/path/path.go @@ -13,6 +13,7 @@ import ( "sync/atomic" "time" "unsafe" + "runtime" cmds "github.com/bittorrent/go-btfs-cmds" @@ -95,7 +96,7 @@ var PathCmd = &cmds.Command{ Tagline: "Modify the Host storage folder path for BTFS client.", ShortDescription: ` The default local repository path is located at ~/.btfs folder, in order to -improve the hard disk space usage, provide the function to change the original +improve the hard disk space usage, provide the function to change the original storage location, a specified path as a parameter need to be passed. `, }, @@ -490,6 +491,10 @@ func CheckDirEmpty(dirname string) bool { } func SetEnvVariables() { + if runtime.GOOS == "android" { + os.Setenv("HOME","/data/data/com.justshare/files/home") // $HOME path definition only + } + //TODO: Pending to add $HOME path for iOS if CheckExist(PropertiesFileName) { btfsPath = ReadProperties(PropertiesFileName) btfsPath = strings.Trim(btfsPath, " \n\r") diff --git a/core/commands/storage/stats/stats.go b/core/commands/storage/stats/stats.go index bb16b3a..d7f0da0 100644 --- a/core/commands/storage/stats/stats.go +++ b/core/commands/storage/stats/stats.go @@ -2,6 +2,7 @@ package stats import ( "context" + "errors" "sort" "strconv" "strings" @@ -24,6 +25,7 @@ import ( const ( localInfoOnlyOptionName = "local-only" + versionOptionName = "version" ) // Storage Stats @@ -61,12 +63,12 @@ This command synchronize node stats from network(hub) to local node data store.` return err } - return SyncStats(req.Context, cfg, n, env) + return SyncStats(req.Context, cfg, n, env, true) }, } -func SyncStats(ctx context.Context, cfg *config.Config, node *core.IpfsNode, env cmds.Environment) error { - sr, err := hub.QueryStats(ctx, node) +func SyncStats(ctx context.Context, cfg *config.Config, node *core.IpfsNode, env cmds.Environment, v2 bool) error { + sr, err := hub.QueryStats(ctx, node, v2) if err != nil { return err } @@ -93,6 +95,34 @@ func SyncStats(ctx context.Context, cfg *config.Config, node *core.IpfsNode, env return SaveHostStatsIntoDatastore(ctx, node, node.Identity.Pretty(), hs) } +func GetNowStats(ctx context.Context, cfg *config.Config, node *core.IpfsNode, env cmds.Environment, V2 bool) (hs *nodepb.StorageStat_Host, err error) { + sr, err := hub.QueryStats(ctx, node, V2) + if err != nil { + return nil, err + } + stat, err := corerepo.RepoStat(ctx, node) + if err != nil { + return nil, err + } + //cfgRoot, err := cmdenv.GetConfigRoot(env) + //if err != nil { + // return nil, err + //} + //du, err := disk.UsageWithContext(ctx, cfgRoot) + //if err != nil { + // return nil, err + //} + hs = &nodepb.StorageStat_Host{ + Online: cfg.Experimental.StorageHostEnabled, + StorageUsed: int64(stat.RepoSize), + StorageCap: int64(stat.StorageMax), + StorageDiskTotal: int64(100000000000), + StorageDiskAvailable: int64(100000000000), + } + hs.StorageStat_HostStats = sr.StorageStat_HostStats + return hs, nil +} + // sub-commands: btfs storage stats info var storageStatsInfoCmd = &cmds.Command{ Helptext: cmds.HelpText{ @@ -103,6 +133,7 @@ This command get node stats in the network from the local node data store.`, Arguments: []cmds.Argument{}, Options: []cmds.Option{ cmds.BoolOption(localInfoOnlyOptionName, "l", "Return only the locally available disk stats without querying/returning the network stats.").WithDefault(false), + cmds.IntOption(versionOptionName, "v", "Get new hub score level.").WithDefault(2), }, RunTimeout: 30 * time.Second, Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { @@ -116,15 +147,20 @@ This command get node stats in the network from the local node data store.`, return err } - local, _ := req.Options[localInfoOnlyOptionName].(bool) - var hs *nodepb.StorageStat_Host - if !local { - hs, err = GetHostStatsFromDatastore(req.Context, n, n.Identity.Pretty()) - if err != nil { - return err - } + var v2Flag bool + v, _ := req.Options[versionOptionName].(int) + if v == 1 { + v2Flag = false + } else if v == 2 { + v2Flag = true } else { - hs = &nodepb.StorageStat_Host{} + return errors.New("version should be 1 or 2, not other. ") + } + + var hs *nodepb.StorageStat_Host + hs, err = GetNowStats(req.Context, cfg, n, env, v2Flag) + if err != nil { + return err } // Refresh latest repo stats diff --git a/core/commands/storage/upload/helper/hosts_helper.go b/core/commands/storage/upload/helper/hosts_helper.go index 3c33146..a1d92b3 100644 --- a/core/commands/storage/upload/helper/hosts_helper.go +++ b/core/commands/storage/upload/helper/hosts_helper.go @@ -8,7 +8,7 @@ import ( "sync" "time" - // "github.com/bittorrent/go-btfs/chain" + "github.com/bittorrent/go-btfs/chain" "github.com/bittorrent/go-btfs/core/commands/storage/helper" "github.com/bittorrent/go-btfs/core/corehttp/remote" @@ -36,10 +36,10 @@ type CustomizedHostsProvider struct { } func (p *CustomizedHostsProvider) NextValidHost() (string, error) { - //myPeerId, err := peer.IDB58Decode(p.cp.Cfg.Identity.PeerID) - //if err != nil { - // return "", err - //} + myPeerId, err := peer.IDB58Decode(p.cp.Cfg.Identity.PeerID) + if err != nil { + return "", err + } for true { if index, err := p.AddIndex(); err == nil { @@ -48,10 +48,10 @@ func (p *CustomizedHostsProvider) NextValidHost() (string, error) { continue } // If my vault is not compatible with the host's one, skip - //isVaultCompatible, err := chain.SettleObject.Factory.IsVaultCompatibleBetween(p.cp.Ctx, myPeerId, id) - //if err != nil || !isVaultCompatible { - // continue - //} + isVaultCompatible, err := chain.SettleObject.Factory.IsVaultCompatibleBetween(p.cp.Ctx, myPeerId, id) + if err != nil || !isVaultCompatible { + continue + } if err := p.cp.Api.Swarm().Connect(p.cp.Ctx, peer.AddrInfo{ID: id}); err != nil { p.hosts = append(p.hosts, p.hosts[index]) continue @@ -169,10 +169,10 @@ func (p *HostsProvider) AddIndex() (int, error) { } func (p *HostsProvider) PickFromBackupHosts() (string, error) { - //myPeerId, err := peer.IDB58Decode(p.cp.Cfg.Identity.PeerID) - //if err != nil { - // return "", err - // } + myPeerId, err := peer.IDB58Decode(p.cp.Cfg.Identity.PeerID) + if err != nil { + return "", err + } for true { host, err := func() (string, error) { @@ -196,10 +196,10 @@ func (p *HostsProvider) PickFromBackupHosts() (string, error) { continue } // If my vault is not compatible with the host's one, skip - //isVaultCompatible, err := chain.SettleObject.Factory.IsVaultCompatibleBetween(p.ctx, myPeerId, id) - //if err != nil || !isVaultCompatible { - // continue - //} + isVaultCompatible, err := chain.SettleObject.Factory.IsVaultCompatibleBetween(p.ctx, myPeerId, id) + if err != nil || !isVaultCompatible { + continue + } if err := p.cp.Api.Swarm().Connect(ctx, peer.AddrInfo{ID: id}); err != nil { continue } @@ -227,10 +227,10 @@ func (p *HostsProvider) PickFromBackupHosts() (string, error) { } func (p *HostsProvider) NextValidHost() (string, error) { - //myPeerId, err := peer.IDB58Decode(p.cp.Cfg.Identity.PeerID) - //if err != nil { - // return "", err - //} + myPeerId, err := peer.IDB58Decode(p.cp.Cfg.Identity.PeerID) + if err != nil { + return "", err + } endOfBackup := false LOOP: @@ -260,10 +260,10 @@ LOOP: continue } // If my vault is not compatible with the host's one, skip - //isVaultCompatible, err := chain.SettleObject.Factory.IsVaultCompatibleBetween(p.ctx, myPeerId, id) - //if err != nil || !isVaultCompatible { - // continue - //} + isVaultCompatible, err := chain.SettleObject.Factory.IsVaultCompatibleBetween(p.ctx, myPeerId, id) + if err != nil || !isVaultCompatible { + continue + } ctx, _ := context.WithTimeout(p.ctx, 3*time.Second) if err := p.cp.Api.Swarm().Connect(ctx, peer.AddrInfo{ID: id}); err != nil { p.Lock() diff --git a/core/commands/storage/upload/upload/do_waitupload.go b/core/commands/storage/upload/upload/do_waitupload.go index 21035f3..381e7fd 100644 --- a/core/commands/storage/upload/upload/do_waitupload.go +++ b/core/commands/storage/upload/upload/do_waitupload.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "math" - "sync" "time" "github.com/bittorrent/go-btfs/core/commands/storage/upload/helper" @@ -136,11 +135,10 @@ func waitUpload(rss *sessions.RenterSession, offlineSigning bool, fsStatus *guar } // pay in cheque - var wg sync.WaitGroup - wg.Add(1) if err := rss.To(sessions.RssToPayEvent); err != nil { return err } + var errC = make(chan error) go func() { err = func() error { return payInCheque(rss) @@ -149,10 +147,16 @@ func waitUpload(rss *sessions.RenterSession, offlineSigning bool, fsStatus *guar fmt.Println("payInCheque error:", err) } fmt.Println("payInCheque done") - wg.Done() + errC <- err }() - wg.Wait() - + err = <-errC + if err != nil { + if fsmErr := rss.To(sessions.RssToErrorEvent); fsmErr != nil { + log.Errorf("fsm transfer error:%v", fsmErr) + } + log.Errorf("payInCheque error:%v", err) + return err + } // Complete if err := rss.To(sessions.RssToCompleteEvent); err != nil { return err diff --git a/core/commands/test.go b/core/commands/test.go index f40810e..d08f50d 100644 --- a/core/commands/test.go +++ b/core/commands/test.go @@ -74,7 +74,14 @@ var testHostsCmd = &cmds.Command{ if err != nil { return err } - fmt.Println("get hosts: ", nodes) + + fmt.Println("len(nodes) = ", len(nodes)) + for i := range nodes { + fmt.Printf("nodes[%d] = %+v", i, nodes[i]) + if i >= 5 { + break + } + } return cmds.EmitOnce(res, &TestOutput{"get hosts ok"}) }, @@ -109,7 +116,6 @@ func getHosts(req *cmds.Request, env cmds.Environment) ([]*hubpb.Host, error) { if err != nil { return nil, err } - return nodes, nil } diff --git a/core/corehttp/webui.go b/core/corehttp/webui.go index ca4a4b1..fd19c6d 100644 --- a/core/corehttp/webui.go +++ b/core/corehttp/webui.go @@ -1,10 +1,11 @@ package corehttp -const WebUIPath = "/btfs/QmXsvmvTTzciHEdbDCCMo55MfrEQ6qnct8B4Wt9aJwHoMY" // v2.2.0 +const WebUIPath = "/btfs/QmaK77EYUHxKweLFvRY8gbcMTx2qEb7p4S5aWPN6EHX7T1" // v2.2.1 // this is a list of all past webUI paths. var WebUIPaths = []string{ WebUIPath, + "/btfs/QmXsvmvTTzciHEdbDCCMo55MfrEQ6qnct8B4Wt9aJwHoMY", // v2.2.0 "/btfs/QmZM3CcoWPHiu9E8ugS76a2csooKEAp5YQitgjQC849h4b", // v2.1.3 "/btfs/QmW3VGCuvfhAJcJZRYQeEjJnjQG27kHNhBasrF2TwGniTT", // v2.1.2 "/btfs/QmWDZ94ZMAjts3WSPbFdLUbfLMYbygJR7BNEygVJqxuqfw", // v2.1.1 diff --git a/core/hub/settings.go b/core/hub/settings.go index 9ecf498..d6ace4c 100644 --- a/core/hub/settings.go +++ b/core/hub/settings.go @@ -15,6 +15,7 @@ func GetHostSettings(ctx context.Context, addr, peerId string) (*nodepb.Node_Set err := grpc.HubQueryClient(addr).WithContext(ctx, func(ctx context.Context, client hubpb.HubQueryServiceClient) error { req := new(hubpb.SettingsReq) req.Id = peerId + req.NewVersion = hubpb.HubRouter_V2 resp, err := client.GetSettings(ctx, req) if err != nil { return err diff --git a/core/hub/settings_test.go b/core/hub/settings_test.go index 53530f7..9cd9e7f 100644 --- a/core/hub/settings_test.go +++ b/core/hub/settings_test.go @@ -2,6 +2,7 @@ package hub import ( "context" + "fmt" "reflect" "testing" @@ -14,6 +15,8 @@ func TestGetSettings(t *testing.T) { if err != nil { t.Fatal(err) } + fmt.Printf("GetHostSettings, ns = %+v \n", ns) + defNs := &nodepb.Node_Settings{StoragePriceAsk: 125000, StorageTimeMin: 30, StoragePriceDefault: 125000} if !reflect.DeepEqual(ns, defNs) { t.Fatal("default settings not equal") diff --git a/core/hub/sync.go b/core/hub/sync.go index 404ca53..ff8cd2f 100644 --- a/core/hub/sync.go +++ b/core/hub/sync.go @@ -2,7 +2,6 @@ package hub import ( "context" - "encoding/json" "fmt" "strings" @@ -31,10 +30,6 @@ const ( // if valid, and if local is true and mode is empty, return prefix for storing such // information into local datastore. func CheckValidMode(mode string, local bool) (hubpb.HostsReq_Mode, string, error) { - if json.Valid([]byte(mode)) { - return -1, "mixture", nil - } - if mode == HubModeAll && local { return -1, "", nil } @@ -61,9 +56,10 @@ func QueryHosts(ctx context.Context, node *core.IpfsNode, mode string) ([]*hubpb err = grpc.HubQueryClient(config.Services.HubDomain).WithContext(ctx, func(ctx context.Context, client hubpb.HubQueryServiceClient) error { resp, err = client.GetHosts(ctx, &hubpb.HostsReq{ - Id: node.Identity.Pretty(), - Mode: hrm, - Version: version.CurrentVersionNumber, + Id: node.Identity.Pretty(), + Mode: hrm, + Version: version.CurrentVersionNumber, + NewVersion: hubpb.HubRouter_V2, }) if err != nil { return err @@ -81,16 +77,23 @@ func QueryHosts(ctx context.Context, node *core.IpfsNode, mode string) ([]*hubpb } // QueryStats queries the BTFS-Hub to retrieve the latest storage stats on this host. -func QueryStats(ctx context.Context, node *core.IpfsNode) (*hubpb.StatsResp, error) { +func QueryStats(ctx context.Context, node *core.IpfsNode, v2 bool) (*hubpb.StatsResp, error) { config, err := node.Repo.Config() if err != nil { return nil, err } + + newVersion := hubpb.HubRouter_V2 + if !v2 { + newVersion = hubpb.HubRouter_V1 + } + var resp *hubpb.StatsResp err = grpc.HubQueryClient(config.Services.HubDomain).WithContext(ctx, func(ctx context.Context, client hubpb.HubQueryServiceClient) error { resp, err = client.GetStats(ctx, &hubpb.StatsReq{ - Id: node.Identity.Pretty(), + Id: node.Identity.Pretty(), + NewVersion: newVersion, }) if err != nil { return err diff --git a/go.mod b/go.mod index a274602..57b63b2 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec // indirect github.com/TRON-US/go-btfs-api v0.3.0 github.com/TRON-US/go-btfs-chunker v0.3.0 - github.com/TRON-US/go-btfs-config v0.11.10 + github.com/TRON-US/go-btfs-config v0.11.11 github.com/TRON-US/go-btfs-files v0.2.0 github.com/TRON-US/go-btfs-pinner v0.1.1 github.com/TRON-US/go-btns v0.1.1 @@ -121,11 +121,12 @@ require ( github.com/prometheus/client_golang v1.11.0 github.com/prometheus/common v0.26.0 github.com/shirou/gopsutil/v3 v3.20.12 + github.com/simbadMarino/go-homedir v0.0.0-20180124010941-45071c14e041 // indirect github.com/status-im/keycard-go v0.0.0-20200402102358-957c09536969 github.com/stretchr/testify v1.7.0 github.com/syndtr/goleveldb v1.0.1-0.20210305035536-64b5b1c73954 github.com/thedevsaddam/gojsonq/v2 v2.5.2 - github.com/tron-us/go-btfs-common v0.8.9 + github.com/tron-us/go-btfs-common v0.8.10 github.com/tron-us/go-common/v2 v2.3.0 github.com/tron-us/protobuf v1.3.7 github.com/tyler-smith/go-bip32 v0.0.0-20170922074101-2c9cfd177564 diff --git a/go.sum b/go.sum index 6b0eef7..f02ab49 100644 --- a/go.sum +++ b/go.sum @@ -89,8 +89,8 @@ github.com/TRON-US/go-btfs-api v0.3.0/go.mod h1:surmr8ztnpbVY7y2H7dbb7npNXfdaV0U github.com/TRON-US/go-btfs-chunker v0.3.0 h1:06/rAYKtC3BQRYVxMtEKvqFFHhSB+XKcqt3JZ0CjD4o= github.com/TRON-US/go-btfs-chunker v0.3.0/go.mod h1:m0xvt42kqLskWsLF6SQ51AA9cqPzWoweydOcDgSDX/U= github.com/TRON-US/go-btfs-config v0.6.0/go.mod h1:82nKCMRhsgY0I8DCasIUpSr6ZP9iHLsZJSMUxytMpEw= -github.com/TRON-US/go-btfs-config v0.11.10 h1:VPxc6y6WRHxww8DAugLnxdwaeqDfauNjUnL/9ZRrQTU= -github.com/TRON-US/go-btfs-config v0.11.10/go.mod h1:9y6osJENDCjulSNJjSSt1J8OK+ADRatBdYPXRDewbko= +github.com/TRON-US/go-btfs-config v0.11.11 h1:vPMnSi5ZO/lzG/a4nQHDUXQYo+lH7tEYxCY+7EsC4r8= +github.com/TRON-US/go-btfs-config v0.11.11/go.mod h1:9y6osJENDCjulSNJjSSt1J8OK+ADRatBdYPXRDewbko= github.com/TRON-US/go-btfs-files v0.1.1/go.mod h1:tD2vOKLcLCDNMn9rrA27n2VbNpHdKewGzEguIFY+EJ0= github.com/TRON-US/go-btfs-files v0.2.0 h1:JZ+F0gX8iPmUf1OlrdOdsA8GMGxCHhwQ03jEWWEgVLE= github.com/TRON-US/go-btfs-files v0.2.0/go.mod h1:Qx+rTOIC0xl3ZkosGcEoB4hqExZmTONErPys8K5suEc= @@ -1304,6 +1304,8 @@ github.com/shurcooL/sanitized_anchor_name v0.0.0-20170918181015-86672fcb3f95/go. github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/shurcooL/users v0.0.0-20180125191416-49c67e49c537/go.mod h1:QJTqeLYEDaXHZDBsXlPCDqdhQuJkuw4NOtaxYe3xii4= github.com/shurcooL/webdavfs v0.0.0-20170829043945-18c3829fa133/go.mod h1:hKmq5kWdCj2z2KEozexVbfEZIWiTjhE0+UjmZgPqehw= +github.com/simbadMarino/go-homedir v0.0.0-20180124010941-45071c14e041 h1:XO22+GjP6/IGDpuyttO7NgAehqQfOGubG1IYwLAppdI= +github.com/simbadMarino/go-homedir v0.0.0-20180124010941-45071c14e041/go.mod h1:+U0IPY5pvQpRr046DIzfLlHDg3rRPrFuh5U3QDrEy5Y= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= @@ -1374,8 +1376,8 @@ github.com/tklauser/numcpus v0.2.2/go.mod h1:x3qojaO3uyYt0i56EW/VUYs7uBvdl2fkfZF github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tron-us/go-btfs-common v0.2.11/go.mod h1:9ND33JahGMg52sCC2/gO5DakLsd1Pg2lVe2CihW7lBE= github.com/tron-us/go-btfs-common v0.3.7/go.mod h1:FbYoo6ZrtnJH3TKdyJTGQrUP2rbwNVATQpxplwaYQ/c= -github.com/tron-us/go-btfs-common v0.8.9 h1:6bFJ2J5XNvrawKmA8GmpNlWNDqGMiGRa7fp8JvHTlnk= -github.com/tron-us/go-btfs-common v0.8.9/go.mod h1:xnIFfbMRS5VsF948fBHPcYIeYGZkQgaJ6NIEGIPfYUs= +github.com/tron-us/go-btfs-common v0.8.10 h1:jr8DQja8H/UVH72vzxrNf2LmmmS5M4g3xrUAT7wUPVw= +github.com/tron-us/go-btfs-common v0.8.10/go.mod h1:xnIFfbMRS5VsF948fBHPcYIeYGZkQgaJ6NIEGIPfYUs= github.com/tron-us/go-common/v2 v2.0.5/go.mod h1:GiKX9noBLHotkZAU+7ET4h7N0DYWnm3OcGHOFJg1Q68= github.com/tron-us/go-common/v2 v2.1.9/go.mod h1:YIEJZF9Ph79g0zZWOvfNDtJhvO5OqSNPAb/TM1i+KvQ= github.com/tron-us/go-common/v2 v2.3.0 h1:bt7WYyOWG6NleHsBB1B/iR1m+mwe3JsaTv/HFbFgxYw= diff --git a/repo/fsrepo/misc.go b/repo/fsrepo/misc.go index 38b893b..98cb424 100644 --- a/repo/fsrepo/misc.go +++ b/repo/fsrepo/misc.go @@ -2,7 +2,7 @@ package fsrepo import ( "os" - + "runtime" "github.com/mitchellh/go-homedir" ) @@ -11,6 +11,12 @@ import ( // repo path. func BestKnownPath() (string, error) { btfsPath := "~/Documents/.btfs" + if runtime.GOOS == "darwin" { //TODO: Leave only ./btfs path by defining properly the $HOME dir for iOS in path.go file + btfsPath = "~/Documents/.btfs" //iOS path + } + if runtime.GOOS == "android" { + btfsPath = "~/.btfs" //Android path + } if os.Getenv("BTFS_PATH") != "" { btfsPath = os.Getenv("BTFS_PATH") } diff --git a/reportstatus/checkreport.go b/reportstatus/checkreport.go deleted file mode 100644 index 47717ba..0000000 --- a/reportstatus/checkreport.go +++ /dev/null @@ -1,46 +0,0 @@ -package reportstatus - -import ( - config "github.com/TRON-US/go-btfs-config" - "github.com/bittorrent/go-btfs/chain" - "github.com/bittorrent/go-btfs/core/commands" -) - -// CheckExistLastOnline sync conf and lastOnlineInfo -func CheckExistLastOnline(cfg *config.Config, configRoot string, chainId int64) error { - lastOnline, err := chain.GetLastOnline() - if err != nil { - return err - } - - // if nil, set config online status config - if lastOnline == nil { - var reportOnline bool - var reportStatusContract bool - if cfg.Experimental.StorageHostEnabled { - reportOnline = true - reportStatusContract = true - } - - var onlineServerDomain string - if chainId == 199 { - onlineServerDomain = config.DefaultServicesConfig().OnlineServerDomain - } else { - onlineServerDomain = config.DefaultServicesConfigTestnet().OnlineServerDomain - } - - err = commands.SyncConfigOnlineCfg(configRoot, onlineServerDomain, reportOnline, reportStatusContract) - if err != nil { - return err - } - } - - // if nil, set last online info - if lastOnline == nil { - err = serv.checkLastOnlineInfo(cfg.Identity.PeerID, cfg.Identity.BttcAddr) - if err != nil { - return err - } - } - return nil -} diff --git a/reportstatus/reportstatus.go b/reportstatus/reportstatus.go index 7eaa7ab..b302ee0 100644 --- a/reportstatus/reportstatus.go +++ b/reportstatus/reportstatus.go @@ -4,7 +4,6 @@ import ( "context" "encoding/hex" "fmt" - onlinePb "github.com/tron-us/go-btfs-common/protos/online" "math/big" "strings" "time" @@ -14,6 +13,7 @@ import ( "github.com/bittorrent/go-btfs/reportstatus/abi" "github.com/bittorrent/go-btfs/transaction" "github.com/ethereum/go-ethereum/common" + onlinePb "github.com/tron-us/go-btfs-common/protos/online" logging "github.com/ipfs/go-log" ) @@ -23,6 +23,8 @@ var log = logging.Logger("report-status-contract:") var ( statusABI = transaction.ParseABIUnchecked(abi.StatusHeartABI) serv *service + + startTime = time.Now() ) const ( @@ -30,14 +32,8 @@ const ( //ReportStatusTime = 60 * time.Second // 10 * time.Minute ) -func Init(transactionService transaction.Service, cfg *config.Config, configRoot string, statusAddress common.Address, chainId int64) error { - New(statusAddress, transactionService, cfg) - - err := CheckExistLastOnline(cfg, configRoot, chainId) - if err != nil { - return err - } - return nil +func Init(transactionService transaction.Service, cfg *config.Config, statusAddress common.Address) Service { + return New(statusAddress, transactionService, cfg) } func isReportStatusEnabled(cfg *config.Config) bool { @@ -55,6 +51,9 @@ type Service interface { // CheckReportStatus check report status heart info to statusContract CheckReportStatus() error + + // CheckLastOnlineInfo check last online info. + CheckLastOnlineInfo(peerId, bttcAddr string) error } func New(statusAddress common.Address, transactionService transaction.Service, cfg *config.Config) Service { @@ -139,15 +138,6 @@ func (s *service) ReportStatus() (common.Hash, error) { if err != nil { return common.Hash{}, err } - - // WaitForReceipt takes long time - go func() { - defer func() { - if r := recover(); r != nil { - log.Errorf("ReportHeartStatus recovered:%+v", err) - } - }() - }() return txHash, nil } @@ -161,8 +151,17 @@ func getGasPrice(request *transaction.TxRequest) *big.Int { return gasPrice } -// report heart status -func (s *service) checkLastOnlineInfo(peerId, bttcAddr string) error { +func CmdReportStatus() error { + _, err := serv.ReportStatus() + if err != nil { + log.Errorf("ReportStatus err:%+v", err) + return err + } + return nil +} + +// CheckLastOnlineInfo report heart status +func (s *service) CheckLastOnlineInfo(peerId, bttcAddr string) error { callData, err := statusABI.Pack("getStatus", peerId) if err != nil { return err @@ -203,15 +202,6 @@ func (s *service) checkLastOnlineInfo(peerId, bttcAddr string) error { return err } } - - // WaitForReceipt takes long time - go func() { - defer func() { - if r := recover(); r != nil { - log.Errorf("getStatus recovered:%+v", err) - } - }() - }() return nil } @@ -240,15 +230,6 @@ func (s *service) genHashExt(ctx context.Context) (common.Hash, error) { if err != nil { return common.Hash{}, err } - - // WaitForReceipt takes long time - go func() { - defer func() { - if r := recover(); r != nil { - log.Errorf("genHashExt recovered:%+v", err) - } - }() - }() return common.Hash{}, nil } @@ -274,10 +255,15 @@ func cycleCheckReport() { report, err := chain.GetReportStatus() //fmt.Printf("... ReportStatus, CheckReportStatus report: %+v err:%+v \n", report, err) if err != nil { + log.Errorf("GetReportStatus err:%+v", err) continue } now := time.Now() + if now.Sub(startTime) < 2*time.Hour { + continue + } + nowUnixMod := now.Unix() % 86400 // report only 1 hour every, and must after 10 hour. if nowUnixMod > report.ReportStatusSeconds && @@ -286,6 +272,7 @@ func cycleCheckReport() { err = serv.CheckReportStatus() if err != nil { + log.Errorf("CheckReportStatus err:%+v", err) continue } } diff --git a/settlement/swap/vault/chequestore.go b/settlement/swap/vault/chequestore.go index e47d187..4a572e3 100644 --- a/settlement/swap/vault/chequestore.go +++ b/settlement/swap/vault/chequestore.go @@ -157,14 +157,11 @@ func (s *chequeStore) ReceiveCheque(ctx context.Context, cheque *SignedCheque, p } else { lastCumulativePayout = lastReceivedCheque.CumulativePayout } - - // check this cheque is actually increasing in value + // check this cheque is actually increasing in value by local storage amount := big.NewInt(0).Sub(cheque.CumulativePayout, lastCumulativePayout) - if amount.Cmp(big.NewInt(0)) <= 0 { return nil, ErrChequeNotIncreasing } - // blockchain calls below contract := newVaultContract(cheque.Vault, s.transactionService) // this does not change for the same vault @@ -199,6 +196,12 @@ func (s *chequeStore) ReceiveCheque(ctx context.Context, cheque *SignedCheque, p return nil, ErrBouncingCheque } + // check this cheque is actually increasing in value by blockchain in case of the host migrate to another machine + // https://github.com/bittorrent/go-btfs/issues/187 + if cheque.CumulativePayout.Cmp(alreadyPaidOut) <= 0 { + return nil, ErrChequeNotIncreasing + } + // store the accepted cheque err = s.store.Put(lastReceivedChequeKey(cheque.Vault), cheque) if err != nil { diff --git a/settlement/swap/vault/vault.go b/settlement/swap/vault/vault.go index af2601f..3be20be 100644 --- a/settlement/swap/vault/vault.go +++ b/settlement/swap/vault/vault.go @@ -274,15 +274,13 @@ func (s *service) Issue(ctx context.Context, beneficiary common.Address, amount defer s.unreserveTotalIssued(amount) var cumulativePayout *big.Int - lastCheque, err := s.LastCheque(beneficiary) + // cumulativePayout should get from blockchain rather than local storage in case of the loss of the local storage. + // https://github.com/bittorrent/go-btfs/issues/187 + alreadyPaidOut, err := s.contract.PaidOut(ctx, beneficiary) if err != nil { - if err != ErrNoCheque { - return nil, err - } - cumulativePayout = big.NewInt(0) - } else { - cumulativePayout = lastCheque.CumulativePayout + return nil, err } + cumulativePayout = alreadyPaidOut // increase cumulativePayout by amount cumulativePayout = cumulativePayout.Add(cumulativePayout, amount) diff --git a/settlement/swap/vault/vault_test.go b/settlement/swap/vault/vault_test.go index d4ada48..3e7c60a 100644 --- a/settlement/swap/vault/vault_test.go +++ b/settlement/swap/vault/vault_test.go @@ -194,7 +194,7 @@ func TestVaultIssue(t *testing.T) { store := storemock.NewStateStore() amount := big.NewInt(20) amount2 := big.NewInt(30) - expectedCumulative := big.NewInt(50) + // expectedCumulative := big.NewInt(50) sig := common.Hex2Bytes("0xffff") chequeSigner := &chequeSignerMock{} @@ -203,10 +203,13 @@ func TestVaultIssue(t *testing.T) { transactionmock.WithABICallSequence( transactionmock.ABICall(&vaultABI, address, big.NewInt(100).FillBytes(make([]byte, 32)), "totalbalance"), transactionmock.ABICall(&vaultABI, address, big.NewInt(0).FillBytes(make([]byte, 32)), "totalPaidOut"), + transactionmock.ABICall(&vaultABI, address, big.NewInt(0).FillBytes(make([]byte, 32)), "paidOut", beneficiary), transactionmock.ABICall(&vaultABI, address, big.NewInt(100).FillBytes(make([]byte, 32)), "totalbalance"), transactionmock.ABICall(&vaultABI, address, big.NewInt(0).FillBytes(make([]byte, 32)), "totalPaidOut"), + transactionmock.ABICall(&vaultABI, address, big.NewInt(0).FillBytes(make([]byte, 32)), "paidOut", beneficiary), transactionmock.ABICall(&vaultABI, address, big.NewInt(100).FillBytes(make([]byte, 32)), "totalbalance"), transactionmock.ABICall(&vaultABI, address, big.NewInt(0).FillBytes(make([]byte, 32)), "totalPaidOut"), + transactionmock.ABICall(&vaultABI, address, big.NewInt(0).FillBytes(make([]byte, 32)), "paidOut", ownerAdress), ), ), address, @@ -264,7 +267,7 @@ func TestVaultIssue(t *testing.T) { expectedCheque = &vault.SignedCheque{ Cheque: vault.Cheque{ Beneficiary: beneficiary, - CumulativePayout: expectedCumulative, + CumulativePayout: amount2, Vault: address, }, Signature: sig, diff --git a/spin/analytics.go b/spin/analytics.go index 814172e..566002c 100644 --- a/spin/analytics.go +++ b/spin/analytics.go @@ -36,6 +36,7 @@ type dcWrap struct { //Server URL for data collection var ( log = logging.Logger("spin") + DC *dcWrap ) // other constants @@ -84,6 +85,7 @@ func Analytics(api iface.CoreAPI, cfgRoot string, node *core.IpfsNode, BTFSVersi dc.api = api dc.pn = new(nodepb.Node) dc.config = configuration + DC = dc if isAnalyticsEnabled(dc.config) { if dc.config.Experimental.Analytics != dc.config.Experimental.StorageHostEnabled { diff --git a/spin/analytics_online.go b/spin/analytics_online.go index 494be87..900fecb 100644 --- a/spin/analytics_online.go +++ b/spin/analytics_online.go @@ -22,7 +22,11 @@ func isReportOnlineEnabled(cfg *config.Config) bool { } func (dc *dcWrap) doSendDataOnline(ctx context.Context, config *config.Config, sm *onlinePb.ReqSignMetrics) error { - cb := cgrpc.OnlineClient(config.Services.OnlineServerDomain) + onlineService := config.Services.OnlineServerDomain + if len(onlineService) <= 0 { + onlineService = chain.GetOnlineServer(config.ChainInfo.ChainId) + } + cb := cgrpc.OnlineClient(onlineService) return cb.WithContext(ctx, func(ctx context.Context, client onlinePb.OnlineServiceClient) error { resp, err := client.UpdateSignMetrics(ctx, sm) if err != nil { @@ -55,7 +59,7 @@ func (dc *dcWrap) doSendDataOnline(ctx context.Context, config *config.Config, s }) } -func (dc *dcWrap) sendDataOnline(node *core.IpfsNode, config *config.Config) { +func (dc *dcWrap) SendDataOnline(node *core.IpfsNode, config *config.Config) { sm, errs, err := dc.doPrepDataOnline(node) if errs == nil { errs = make([]error, 0) @@ -176,7 +180,7 @@ func (dc *dcWrap) collectionAgentOnline(node *core.IpfsNode) { //fmt.Println("") //fmt.Println("--- online agent ---") - dc.sendDataOnline(node, cfg) + dc.SendDataOnline(node, cfg) } } } diff --git a/spin/hosts.go b/spin/hosts.go index 0e2fad3..3d4f357 100644 --- a/spin/hosts.go +++ b/spin/hosts.go @@ -33,7 +33,7 @@ func Hosts(node *core.IpfsNode, env cmds.Environment) { fmt.Printf("Storage host info will be synced at [%s] mode\n", m) go periodicSync(hostSyncPeriod, hostSyncTimeout+hostSortTimeout, "hosts", func(ctx context.Context) error { - _, err := hosts.SyncHostsMixture(ctx, node, m) + _, err := hosts.SyncHosts(ctx, node, m) return err }) } @@ -41,7 +41,7 @@ func Hosts(node *core.IpfsNode, env cmds.Environment) { fmt.Println("Current host stats will be synced") go periodicSync(hostStatsSyncPeriod, hostSyncTimeout, "host stats", func(ctx context.Context) error { - return stats.SyncStats(ctx, cfg, node, env) + return stats.SyncStats(ctx, cfg, node, env, true) }) fmt.Println("Current host settings will be synced") go periodicSync(hostSettingsSyncPeriod, hostSyncTimeout, "host settings", diff --git a/version.go b/version.go index c5e4b7e..9dd672a 100644 --- a/version.go +++ b/version.go @@ -4,7 +4,7 @@ package btfs var CurrentCommit string // CurrentVersionNumber is the current application's version literal -const CurrentVersionNumber = "2.2.0" +const CurrentVersionNumber = "2.2.1" const ApiVersion = "/go-btfs/" + CurrentVersionNumber + "/"