id
stringlengths
2
7
text
stringlengths
17
51.2k
title
stringclasses
1 value
c173400
product, productPassword) if err != nil { return nil, err } ch, err := h.findClientChannel(logger, prod, clientKey, true) if err != nil { return nil, err } var ept data.Endpoint if err := h.db.FindOneTo(&ept, "channel", ch.ID); err != nil { logger.Error(err.Error()) return nil, ErrEndpointNotFound } return &ept, nil }
c173401
country2 = country.UndefinedCountry } prod.Country = &country2 } if prod.Config, err = json.Marshal(config); err != nil { logger.Error(err.Error()) return ErrInternal } if err := h.db.Update(prod); err != nil { logger.Error(err.Error()) return ErrInternal } return nil }
c173402
log.LstdFlags if conf.UTC { flags |= log.LUTC } l.logger = log.New(out, conf.Prefix, flags) l.LoggerBase = base return l, nil }
c173403
} logger, err := NewWriterLogger(conf.WriterConfig, file) if err != nil { file.Close() return nil, nil, err } return logger, file, nil }
c173404
} torClient, err := tor.NewHTTPClient(b.torSocks) return somcsrv.NewClient(torClient, string(hostnameBytes)), nil } return nil, ErrUnknownSOMCType }
c173405
nil case "pmp": return pmp(), nil default: return nil, ErrBadMechanism } }
c173406
name, mapTimeout); err != nil { logger.Error(err.Error()) return ErrAddMapping } logger.Info("mapped network port") go func() { timer := time.NewTimer(mapUpdateInterval) defer func() { timer.Stop() logger.Debug("deleting port mapping") m.DeleteMapping(protocol, extPort, intPort) }() for { select { case <-ctx.Done(): return case <-timer.C: logger.Debug("refreshing port mapping") if err := m.AddMapping(protocol, extPort, intPort, name, mapTimeout); err != nil { logger.Warn("couldn't add" + " port mapping, error: " + err.Error()) } timer.Reset(mapUpdateInterval) } } }() return nil }
c173407
return n.found.AddMapping(protocol, extPort, intPort, name, lifetime) }
c173408
if err := n.wait(); err != nil { return err } return n.found.DeleteMapping(protocol, extPort, intPort) }
c173409
data, err := ioutil.ReadAll(file) if err != nil { return nil, ErrReadFile } return data, nil }
c173410
denied") return nil, ErrAccessDenied } return &h.userRole, nil }
c173411
encryptKeyFunc: encryptKeyFunc, decryptKeyFunc: decryptKeyFunc, userRole: userRole, processor: processor, somcClientBuilder: somcClientBuilder, token: token, } }
c173412
nil { logger.Fatal(err.Error()) } b := &backendInstance{cfg: cfg, ptc: ptc, psc: psc, conn: conn, logger: logger, } go b.connectionControl() return b }
c173413
if ctx == nil { ctx = context.Background() } return context.WithTimeout(ctx, time.Duration(b.cfg.Timeout)*time.Millisecond) }
c173414
defer cancel() return b.conn.ethClient().PendingNonceAt(ctx, account) }
c173415
gasPrice, err := b.conn.ethClient().SuggestGasPrice(ctx2) if err != nil { return nil, fmt.Errorf("failed to get"+ " suggested gas price: %s", err) } return gasPrice, err }
c173416
b.conn.ethClient().EstimateGas(ctx2, call) if err != nil { return 0, fmt.Errorf("failed to estimated gas: %s", err) } return gas, err }
c173417
err := b.psc.CooperativeClose(opts, agent, block, offeringHash, balance, balanceSig, closingSig) if err != nil { return nil, fmt.Errorf("failed to do cooperative close: %s", err) } return tx, nil }
c173418
b.conn.ethClient().TransactionByHash(ctx2, hash) if err != nil { err = fmt.Errorf("failed to get transaction by hash: %s", err) } return tx, pending, err }
c173419
err := b.psc.RegisterServiceOffering(opts, offeringHash, minDeposit, maxSupply, somcType, string(somcData)) if err != nil { return nil, fmt.Errorf( "failed to register service offering: %s", err) } return tx, nil }
c173420
val, err := b.ptc.BalanceOf(opts, owner) if err != nil { err = fmt.Errorf("failed to get PTC balance: %s", err) } return val, err }
c173421
b.addTimeout(opts.Context) defer cancel() opts.Context = ctx2 tx, err := b.ptc.IncreaseApproval(opts, spender, addedVal) if err != nil { return nil, fmt.Errorf("failed to PTC increase approval: %s", err) } return tx, nil }
c173422
val, err := b.psc.BalanceOf(opts, owner) if err != nil { err = fmt.Errorf("failed to get PSC balance: %s", err) } return val, err }
c173423
tx, err := b.psc.AddBalanceERC20(opts, amount) if err != nil { return nil, fmt.Errorf("failed to add ERC20 balance: %s", err) } return tx, nil }
c173424
= b.psc.GetOfferingInfo(opts, hash) active = updateBlockNumber != 0 if err != nil { err = fmt.Errorf("failed to get PSC offering supply: %s", err) } return agentAddr, minDeposit, maxSupply, currentSupply, updateBlockNumber, active, err }
c173425
b.addTimeout(opts.Context) defer cancel() opts.Context = ctx2 return b.psc.GetChannelInfo(opts, client, agent, blockNumber, hash) }
c173426
cancel() return b.conn.ethClient().BalanceAt(ctx2, owner, nil) }
c173427
b.psc.Settle(opts, agent, blockNumber, hash) if err != nil { err = fmt.Errorf("failed to settle"+ " PSC channel: %s", err) } return tx, err }
c173428
tx, err := b.psc.RemoveServiceOffering(opts, offeringHash) if err != nil { err = fmt.Errorf("failed to remove"+ " service offering: %v", err) } return tx, err }
c173429
:= b.addTimeout(opts.Context) defer cancel() opts.Context = ctx2 tx, err := b.psc.PopupServiceOffering(opts, offeringHash, somcType, string(somcData)) if err != nil { err = fmt.Errorf("failed to pop up service offering: %v", err) } return tx, err }
c173430
return b.conn.ethClient().FilterLogs(ctx, q) }
c173431
return b.conn.ethClient().HeaderByNumber(ctx, number) }
c173432
{ return common.HexToAddress(b.cfg.Contract.PTCAddrHex) }
c173433
{ return common.HexToAddress(b.cfg.Contract.PSCAddrHex) }
c173434
db, logger: logger.Add("type", "tor-somc.Handler")} }
c173435
:= data.ChannelKey(ch.Client, ch.Agent, ch.Block, offering.Hash) // internal if err != nil { logger.Add("channel", ch, "offering", offering).Error(err.Error()) return "", ErrInternal } return data.FromBytes(key), nil }
c173436
job.RelatedID, Client: data.HexFromBytes(logChannelCreated.clientAddr.Bytes()), Agent: data.HexFromBytes(logChannelCreated.agentAddr.Bytes()), TotalDeposit: logChannelCreated.deposit.Uint64(), ChannelStatus: data.ChannelActive, ServiceStatus: data.ServicePending, Offering: offering.ID, Block: uint32(ethLog.Block), } if err := tx.Insert(channel); err != nil { logger.Error(err.Error()) return ErrInternal } if err := w.addJob(logger, tx, data.JobAgentPreEndpointMsgCreate, data.JobChannel, channel.ID); err != nil { return err } if err := tx.Commit(); err != nil { logger.Error("unable to commit changes: " + err.Error()) return ErrInternal } return nil }
c173437
w.afterChannelTopUp(job, data.JobAgentAfterChannelTopUp) }
c173438
logger.Error(err.Error()) return ErrTerminateChannel } } channel.ChannelStatus = data.ChannelInChallenge if err = w.db.Update(channel); err != nil { logger.Error(err.Error()) return ErrInternal } return nil }
c173439
err != nil { logger.Error(err.Error()) return ErrInternal } if err := w.incrementCurrentSupply(logger, w.db.Querier, channel.Offering); err != nil { return err } agent, err := w.account(logger, channel.Agent) if err != nil { return err } return w.addJob(logger, nil, data.JobAccountUpdateBalances, data.JobAccount, agent.ID) }
c173440
tx.Querier, channel.Offering); err != nil { return err } agent, err := w.account(logger, channel.Agent) if err != nil { return err } return w.addJob(logger, tx, data.JobAccountUpdateBalances, data.JobAccount, agent.ID) }) }
c173441
"AgentPreServiceSuspend", "job", job) _, err := w.agentUpdateServiceStatus(logger, job, data.JobAgentPreServiceSuspend) return err }
c173442
"AgentPreServiceSuspend", "job", job) _, err := w.agentUpdateServiceStatus(logger, job, data.JobAgentPreServiceUnsuspend) return err }
c173443
w.agentUpdateServiceStatus(logger, job, data.JobAgentPreServiceTerminate) if err != nil { return err } if channel.ReceiptBalance == 0 { return nil } return w.agentCooperativeClose(logger, job, channel) }
c173444
{ logger.Error(err.Error()) return ErrInternal } agent, err := w.account(logger, offering.Agent) if err != nil { return err } return w.addJob(logger, nil, data.JobAccountUpdateBalances, data.JobAccount, agent.ID) }
c173445
agent, err := w.account(logger, offering.Agent) if err != nil { return err } return w.addJob(logger, nil, data.JobAccountUpdateBalances, data.JobAccount, agent.ID) }
c173446
} auth := bind.NewKeyedTransactor(key) auth.GasLimit = w.gasConf.PSC.RemoveServiceOffering auth.GasPrice = new(big.Int).SetUint64(jobDate.GasPrice) tx, err := w.ethBack.PSCRemoveServiceOffering(auth, offeringHash) if err != nil { logger.Add("GasLimit", auth.GasLimit, "GasPrice", auth.GasPrice).Error(err.Error()) return ErrPSCRemoveOffering } offering.Status = data.OfferRemoving if err := w.saveRecord(logger, w.db.Querier, offering); err != nil { return err } return w.saveEthTX(logger, job, tx, "RemoveServiceOffering", job.RelatedType, job.RelatedID, offering.Agent, data.HexFromBytes(w.pscAddr.Bytes())) }
c173447
removePeriod, err := data.ReadUintSetting(w.db.Querier, periodKey) if err != nil { return periodErr } if uint64(updateBlockNumber)+uint64(removePeriod) > lastBlock.Uint64() { return periodErr } return nil }
c173448
w.ethBack.PSCPopupServiceOffering(auth, offeringHash, offering.SOMCType, offering.SOMCData) if err != nil { logger.Add("GasLimit", auth.GasLimit, "GasPrice", auth.GasPrice).Error(err.Error()) return ErrPSCPopUpOffering } offering.Status = data.OfferPoppingUp if err := w.saveRecord(logger, w.db.Querier, offering); err != nil { return err } return w.saveEthTX(logger, job, tx, "PopupServiceOffering", job.RelatedType, job.RelatedID, offering.Agent, data.HexFromBytes(w.pscAddr.Bytes())) }
c173449
hash := data.HexFromBytes(logOfferingPopUp.offeringHash.Bytes()) err = w.db.FindOneTo(&offering, "hash", hash) if err != nil { logger.Error(err.Error()) return ErrInternal } offering.BlockNumberUpdated = ethLog.Block offering.Status = data.OfferPoppedUp return w.saveRecord(logger, w.db.Querier, &offering) }
c173450
fmt.Println(Message(commit, version)) os.Exit(0) } }
c173451
return fmt.Sprintf("%s (%d)", msg, e) } return "unknown error" }
c173452
ok := msgs[e] return msg, ok }
c173453
s.RespondError(logger, w, ErrInternalServerError) return } s.respond(logger, w, &Response{Result: data}) }
c173454
s.respond(logger, w, &Response{Error: err}) }
c173455
payload.OfferingHash, payload.AgentAddress, payload.OpenBlockNumber) logger = logger.Add("channel", ch) if ok && s.isServiceTerminated(logger, w, ch) { return } if !ok || !s.validateChannelForPayment(logger, w, ch, payload) || !s.updateChannelWithPayment(logger, w, ch, payload) { return } s.RespondResult(logger, w, struct{}{}) logger.Info(fmt.Sprintf("received payment: %d, from: %s", payload.Balance, ch.Client)) }
c173456
event = logChannelCloseRequested case eth.ServiceCooperativeChannelClose: event = logCooperativeChannelClose case eth.ServiceUnCooperativeChannelClose: event = logUnCooperativeChannelClose default: return } if event != "" { block, err = m.blockNumber(el.Data, logChannelToppedUp) ok = true } return }
c173457
logger.Warn("unexpected request for offering: " + string(hash)) } return nil, err } return &offering.RawMsg, nil }
c173458
worker.ClientAfterChannelTopUp, data.JobClientPreUncooperativeCloseRequest: worker.ClientPreUncooperativeCloseRequest, data.JobClientAfterUncooperativeCloseRequest: worker.ClientAfterUncooperativeCloseRequest, data.JobClientPreServiceTerminate: worker.ClientPreServiceTerminate, data.JobClientPreServiceSuspend: worker.ClientPreServiceSuspend, data.JobClientPreServiceUnsuspend: worker.ClientPreServiceUnsuspend, data.JobClientAfterOfferingMsgBCPublish: worker.ClientAfterOfferingMsgBCPublish, data.JobClientCompleteServiceTransition: worker.ClientCompleteServiceTransition, // Common jobs. data.JobPreAccountAddBalanceApprove: worker.PreAccountAddBalanceApprove, data.JobPreAccountAddBalance: worker.PreAccountAddBalance, data.JobAfterAccountAddBalance: worker.AfterAccountAddBalance, data.JobPreAccountReturnBalance: worker.PreAccountReturnBalance, data.JobAfterAccountReturnBalance: worker.AfterAccountReturnBalance, data.JobAccountUpdateBalances: worker.AccountUpdateBalances, data.JobDecrementCurrentSupply: worker.DecrementCurrentSupply, data.JobIncrementCurrentSupply: worker.IncrementCurrentSupply, } }
c173459
return 0, err } defer db.Close() return goose.GetDBVersion(db) }
c173460
} last, err := migrations.Last() if err != nil { return err } version = last.Version } return executeMigrationScripts(db, version) }
c173461
pr == nil || interval == 0 { return nil, ErrInput } return &Monitor{ db: db, logger: logger.Add("type", "agent/bill.Monitor"), pr: pr, interval: interval, }, nil }
c173462
time.Sleep(time.Duration(m.interval) * time.Millisecond) } }
c173463
offer.setup_price, offer.unit_price, offer.max_billing_unit_lag HAVING COALESCE(SUM(ses.units_used), 0) / offer.billing_interval - (channels.receipt_balance - offer.setup_price ) / offer.unit_price > offer.max_billing_unit_lag;` return m.processEachChannel(query, m.suspendService) }
c173464
acc ON channels.agent = acc.eth_addr WHERE channels.service_status IN ('suspended') AND channels.channel_status NOT IN ('pending') AND acc.in_use GROUP BY channels.id, offer.billing_interval, offer.setup_price, offer.unit_price, offer.max_billing_unit_lag HAVING COALESCE(SUM(ses.units_used), 0) / offer.billing_interval - (channels.receipt_balance - offer.setup_price) / offer.unit_price <= offer.max_billing_unit_lag;` return m.processEachChannel(query, m.unsuspendService) }
c173465
AND acc.in_use GROUP BY channels.id, offer.max_inactive_time_sec HAVING GREATEST(MAX(ses.last_usage_time), channels.service_changed_time) + (offer.max_inactive_time_sec * INTERVAL '1 second') < now();` return m.processEachChannel(query, m.terminateService) }
c173466
ON channels.agent = acc.eth_addr WHERE channels.service_status = 'suspended' AND channels.channel_status NOT IN ('pending') AND acc.in_use AND channels.service_changed_time + (offer.max_suspended_time * INTERVAL '1 SECOND') < now();` return m.processEachChannel(query, m.terminateService) }
c173467
err != nil { return nil, err } l.LoggerBase = base return l, nil }
c173468
return crypto.Keccak256( []byte("\x19Ethereum Signed Message:\n32"), crypto.Keccak256( []byte("Privatix: receiver closing signature"), clientAddr.Bytes(), blockBytes[:], offeringHash.Bytes(), balanceBytes[:], pscAddr.Bytes(), ), ) }
c173469
logger = logger.Add("externalIP", extIP) timeout := time.Duration(conf.CheckTimeout) * time.Millisecond checkSrv := func(port uint16) { if util.CheckConnection( "tcp", extIP, int(port), timeout) { logger.Info(fmt.Sprintf("port %d is available"+ " on the Internet", port)) return } logger.Warn(fmt.Sprintf("port %d is not available"+ " on the Internet", port)) } for k := range ports { checkSrv(ports[k]) } }
c173470
the public key from the signature pub, err := crypto.Ecrecover(hash[:], sig) if err != nil { return nil, err } return crypto.UnmarshalPubkey(pub) }
c173471
templates, err = h.selectAllFrom( logger, data.TemplateTable, "") } if err != nil { return nil, err } result := make([]data.Template, 0) for _, v := range templates { result = append(result, *v.(*data.Template)) } return result, nil }
c173472
return nil, ErrAccessDenied } err := checkTemplate(logger, template) if err != nil { return nil, err } template.ID = util.NewUUID() template.Hash = data.HexFromBytes(crypto.Keccak256(template.Raw)) err = h.insertObject(template) if err != nil { return nil, err } return &template.ID, nil }
c173473
return nil, ErrBadServiceEndpointAddress } product.ID = util.NewUUID() if err := insert(logger, h.db.Querier, &product); err != nil { return nil, err } return &product.ID, nil }
c173474
= oldProduct.Password } if product.ServiceEndpointAddress != nil && !isValidSEAddress(*product.ServiceEndpointAddress) { return ErrBadServiceEndpointAddress } if err := update(logger, h.db.Querier, &product); err != nil { logger.Error(err.Error()) return ErrInternal } return nil }
c173475
logger.Error(err.Error()) return nil, ErrInternal } products := make([]data.Product, len(result)) for i, item := range result { products[i] = *item.(*data.Product) } return products, nil }
c173476
db, logger: logger, countryConf: countryConf, queue: queue, } }
c173477
auth, keystore.StandardScryptN, keystore.StandardScryptP) if err != nil { return "", err } return FromBytes(encryptedBytes), nil }
c173478
initData(f.connection); err != nil { panic("failed to init database: " + err.Error()) } os.Exit(0) case "db-version": f := readFlags(args) version, err := migration.Version(f.connection) if err != nil { msg := "failed to print database schema version: " panic(msg + err.Error()) } fmt.Println("database schema version:", version) os.Exit(0) } return nil }
c173479
} _, err := n.c.AddPortMapping(strings.ToLower(protocol), intPort, extPort, int(lifetime/time.Second)) return err }
c173480
(err error) { _, err = n.c.AddPortMapping(strings.ToLower(protocol), intPort, 0, 0) return err }
c173481
conf, logger: logger.Add("type", "client/bill.Monitor"), db: db, pr: pr, psc: pscAddr, pw: pw, post: pay.PostCheque, } }
c173482
`SELECT SUM(channels.receipt_balance) FROM channels WHERE channels.offering=$1`, offeringID) }
c173483
JOIN channels ON channels.offering=offerings.id AND offerings.product=$1`, productID) }
c173484
h.uintFromQuery(logger, tkn, `SELECT SUM(channels.receipt_balance) FROM channels`) }
c173485
nil { return err } return exec(string(query), tx) }
c173486
settings, err := h.selectAllFrom( logger, data.SettingTable, settingsCondition) if err != nil { return nil, err } for _, v := range settings { setting := *v.(*data.Setting) result[setting.Key] = SettingUI{setting.Value, PermissionsToString[setting.Permissions]} } return result, err }
c173487
// then setting ignored if settingFromDB.Permissions != data.ReadWrite { continue } setting := settingFromDB setting.Value = v err = tx.Update(&setting) if err != nil { logger.Error(err.Error()) return ErrInternal } } return nil }) if err != nil { return h.catchError(logger, err) } return nil }
c173488
ip := net.ParseIP(s) return ip != nil }
c173489
nil || len(addrs) == 0 { return false } return true }
c173490
str, 10, 16); err != nil { return false } return true }
c173491
if derBlock == nil { break } if derBlock.Type == certificate { cert.Certificate = append(cert.Certificate, derBlock.Bytes) } } if len(cert.Certificate) == 0 { return false } return true }
c173492
:= gojsonschema.Validate(sloader, dloader) return err == nil && result.Valid() && len(result.Errors()) == 0 }
c173493
2, ResponseHeaderTimeout: 8, RequestTimeout: 10, IdleConnTimeout: 30, KeepAliveTimeout: 60, }, } }
c173494
err } defer file.Close() return json.NewDecoder(file).Decode(data) }
c173495
:= json.NewEncoder(file) enc.SetIndent(prefix, indent) return enc.Encode(data) }
c173496
uuid.FromString(s) return err == nil }
c173497
elem = append([]string{filepath.Dir(exe)}, elem...) return filepath.Join(elem...) }
c173498
} return filepath.Dir(filepath.Dir(file)) }
c173499
if err != nil { return "?" } return fmt.Sprintf("%s:%d", rel, line) }