Skip to content

Commit

Permalink
Merge pull request #73 from onemorebsmith/v1.1.7
Browse files Browse the repository at this point in the history
idk
  • Loading branch information
onemorebsmith authored Dec 27, 2022
2 parents 15c3104 + 509ac50 commit 429f9a4
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 16 deletions.
8 changes: 8 additions & 0 deletions cmd/kaspabridge/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log"
"os"
"path"
"time"

"github.com/onemorebsmith/kaspastratum/src/kaspastratum"
"gopkg.in/yaml.v2"
Expand Down Expand Up @@ -37,6 +38,13 @@ func main() {
flag.StringVar(&cfg.HealthCheckPort, "hcp", cfg.HealthCheckPort, `(rarely used) if defined will expose a health check on /readyz, default ""`)
flag.Parse()

if cfg.MinShareDiff == 0 {
cfg.MinShareDiff = 4
}
if cfg.BlockWaitTime == 0 {
cfg.BlockWaitTime = 5 * time.Second // this should never happen due to kas 1s block times
}

log.Println("----------------------------------")
log.Printf("initializing bridge")
log.Printf("\tkaspad: %s", cfg.RPCServer)
Expand Down
23 changes: 21 additions & 2 deletions src/gostratum/default_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package gostratum

import (
"fmt"
"regexp"
"strings"

"github.com/kaspanet/kaspad/util"
"github.com/mattn/go-colorable"
"github.com/onemorebsmith/kaspa-pool/src/model"
"github.com/pkg/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
Expand Down Expand Up @@ -61,7 +62,7 @@ func HandleAuthorize(ctx *StratumContext, event JsonRpcEvent) error {
workerName = parts[1]
}
var err error
address, err = model.CleanWallet(address)
address, err = CleanWallet(address)
if err != nil {
return fmt.Errorf("invalid wallet format %s: %w", address, err)
}
Expand Down Expand Up @@ -109,3 +110,21 @@ func SendExtranonce(ctx *StratumContext) {
ctx.Logger.Error(errors.Wrap(err, "failed to set extranonce").Error(), zap.Any("context", ctx))
}
}

var walletRegex = regexp.MustCompile("kaspa:[a-z0-9]+")

func CleanWallet(in string) (string, error) {
_, err := util.DecodeAddress(in, util.Bech32PrefixKaspa)
if err == nil {
return in, nil // good to go
}
if !strings.HasPrefix(in, "kaspa:") {
return CleanWallet("kaspa:" + in)
}

// has kaspa: prefix but other weirdness somewhere
if walletRegex.MatchString(in) {
return in[0:67], nil
}
return "", errors.New("unable to coerce wallet to valid kaspa address")
}
31 changes: 31 additions & 0 deletions src/gostratum/stratum_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,34 @@ func TestNewClient(t *testing.T) {
t.Fatalf("failed to properly respond to authorize")
}
}

func TestWalletValidation(t *testing.T) {
tests := []struct {
in string
expected string
shouldErr bool
}{
{
in: "kaspa:qqayxgcjfh6d7uxpj4w3qzjvx73vdehfx22fl6cacmn44rpj5geg2rxyuhga4,Rig_3784816",
expected: "kaspa:qqayxgcjfh6d7uxpj4w3qzjvx73vdehfx22fl6cacmn44rpj5geg2rxyuhga4",
},
{
in: "kaspa:qqkrl0er5ka5snd55gr9rcf6rlpx8nln8gf3jxf83w4dc0khfqmauy6qs83zm,Rig_3784816",
expected: "kaspa:qqkrl0er5ka5snd55gr9rcf6rlpx8nln8gf3jxf83w4dc0khfqmauy6qs83zm",
},
{
in: "qqkrl0er5ka5snd55gr9rcf6rlpx8nln8gf3jxf83w4dc0khfqmauy6qs83zm,Rig_3784816",
expected: "kaspa:qqkrl0er5ka5snd55gr9rcf6rlpx8nln8gf3jxf83w4dc0khfqmauy6qs83zm",
},
}

for _, v := range tests {
cleaned, err := CleanWallet(v.in)
if err != nil && !v.shouldErr {
t.Fatalf("Unexpected error for wallet %+v", v)
}
if cleaned != v.expected {
t.Fatalf("expected %s, got %s", v.expected, cleaned)
}
}
}
8 changes: 4 additions & 4 deletions src/kaspastratum/client_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package kaspastratum

import (
"fmt"
"math"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"math"

"github.com/onemorebsmith/kaspastratum/src/gostratum"
"github.com/pkg/errors"
Expand Down Expand Up @@ -36,7 +36,7 @@ func newClientListener(logger *zap.SugaredLogger, shareHandler *shareHandler, mi
logger: logger,
minShareDiff: minShareDiff,
extranonceSize: extranonceSize,
maxExtranonce: int32(math.Pow(2, (8 * math.Min(float64(extranonceSize), 3))) - 1),
maxExtranonce: int32(math.Pow(2, (8*math.Min(float64(extranonceSize), 3))) - 1),
nextExtranonce: 0,
clientLock: sync.RWMutex{},
shareHandler: shareHandler,
Expand Down Expand Up @@ -64,7 +64,7 @@ func (c *clientListener) OnConnect(ctx *gostratum.StratumContext) {
ctx.Logger = ctx.Logger.With(zap.Int("client_id", int(ctx.Id)))

if c.extranonceSize > 0 {
ctx.Extranonce = fmt.Sprintf("%0*x", c.extranonceSize * 2, extranonce)
ctx.Extranonce = fmt.Sprintf("%0*x", c.extranonceSize*2, extranonce)
}
go func() {
// hacky, but give time for the authorize to go through so we can use the worker name
Expand Down Expand Up @@ -95,7 +95,7 @@ func (c *clientListener) NewBlockAvailable(kapi *KaspaApi) {
if client.WalletAddr == "" {
if time.Since(state.connectTime) > time.Second*20 { // timeout passed
// this happens pretty frequently in gcp/aws land since script-kiddies scrape ports
client.Logger.Warn("client misconfigured, no miner address specified - disconnecting", client.String())
client.Logger.Warn("client misconfigured, no miner address specified - disconnecting", zap.String("client", client.String()))
RecordWorkerError(client.WalletAddr, ErrNoMinerAddress)
client.Disconnect() // invalid configuration, boot the worker
}
Expand Down
15 changes: 8 additions & 7 deletions src/kaspastratum/share_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/onemorebsmith/kaspastratum/src/gostratum"
"github.com/pkg/errors"
"go.uber.org/atomic"
"go.uber.org/zap"
)

type WorkStats struct {
Expand Down Expand Up @@ -70,9 +71,9 @@ func (sh *shareHandler) getCreateStats(ctx *gostratum.StratumContext) *WorkStats
stats.StartTime = time.Now()
sh.stats[ctx.RemoteAddr] = stats

// TODO: not sure this is the best place, nor whether we shouldn't be
// resetting on disconnect
InitWorkerCounters(ctx)
// TODO: not sure this is the best place, nor whether we shouldn't be
// resetting on disconnect
InitWorkerCounters(ctx)
}

sh.statsLock.Unlock()
Expand Down Expand Up @@ -150,14 +151,14 @@ func (sh *shareHandler) HandleSubmit(ctx *gostratum.StratumContext, event gostra

// add extranonce to noncestr if enabled and submitted nonce is shorter than
// expected (16 - <extranonce length> characters)
if (ctx.Extranonce != "") {
if ctx.Extranonce != "" {
extranonce2Len := 16 - len(ctx.Extranonce)
if (len(submitInfo.noncestr) <= extranonce2Len) {
if len(submitInfo.noncestr) <= extranonce2Len {
submitInfo.noncestr = ctx.Extranonce + fmt.Sprintf("%0*s", extranonce2Len, submitInfo.noncestr)
}
}

ctx.Logger.Debug(submitInfo.block.Header.BlueScore, " submit ", submitInfo.noncestr)
//ctx.Logger.Debug(submitInfo.block.Header.BlueScore, " submit ", submitInfo.noncestr)
state := GetMiningState(ctx)
if state.useBigJob {
submitInfo.nonceVal, err = strconv.ParseUint(submitInfo.noncestr, 16, 64)
Expand Down Expand Up @@ -247,7 +248,7 @@ func (sh *shareHandler) submit(ctx *gostratum.StratumContext,
RecordStaleShare(ctx)
return ctx.ReplyStaleShare(eventId)
} else {
ctx.Logger.Warn("block rejected, unknown issue (probably bad pow", err.Error())
ctx.Logger.Warn("block rejected, unknown issue (probably bad pow", zap.Error(err))
sh.getCreateStats(ctx).InvalidShares.Add(1)
sh.overall.InvalidShares.Add(1)
RecordInvalidShare(ctx)
Expand Down
6 changes: 3 additions & 3 deletions src/kaspastratum/stratum_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

const version = "v1.1.6"
const minBlockWaitTime = time.Duration(500) * time.Millisecond
const minBlockWaitTime = 500 * time.Millisecond

type BridgeConfig struct {
StratumPort string `yaml:"stratum_port"`
Expand Down Expand Up @@ -91,7 +91,7 @@ func ListenAndServe(cfg BridgeConfig) error {
handlers[string(gostratum.StratumMethodSubmit)] =
func(ctx *gostratum.StratumContext, event gostratum.JsonRpcEvent) error {
if err := shareHandler.HandleSubmit(ctx, event); err != nil {
ctx.Logger.Error(err) // sink error
ctx.Logger.Sugar().Error(err) // sink error
}
return nil
}
Expand All @@ -101,7 +101,7 @@ func ListenAndServe(cfg BridgeConfig) error {
HandlerMap: handlers,
StateGenerator: MiningStateGenerator,
ClientListener: clientHandler,
Logger: logger,
Logger: logger.Desugar(),
}

ctx, cancel := context.WithCancel(context.Background())
Expand Down

0 comments on commit 429f9a4

Please sign in to comment.