Browse Source

CreateBlockchainAccount&NewRepo

tags/v0.1.8
yuyuanshifu 4 years ago
parent
commit
a2c62f7fed
8 changed files with 216 additions and 2 deletions
  1. +23
    -0
      models/blockchain.go
  2. +1
    -0
      models/models.go
  3. +10
    -0
      models/repo.go
  4. +16
    -1
      models/user.go
  5. +14
    -0
      modules/blockchain/blockchain.go
  6. +145
    -0
      modules/blockchain/resty.go
  7. +6
    -0
      modules/setting/setting.go
  8. +1
    -1
      modules/worker/task.go

+ 23
- 0
models/blockchain.go View File

@@ -0,0 +1,23 @@
package models

import (
"code.gitea.io/gitea/modules/timeutil"
"time"
)

type BlockChain struct {
ID int64 `xorm:"pk autoincr"`
Contributor string `xorm:"INDEX NOT NULL"`
ContractAddress string `xorm:"INDEX NOT NULL"`
Action string `xorm:"INDEX"`
Amount int64 `xorm:"INDEX"`
UserID int64 `xorm:"INDEX"`
RepoID int64 `xorm:"INDEX"`
CreatedUnix timeutil.TimeStamp `xorm:"created"`
UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
DeletedAt time.Time `xorm:"deleted"`

User *User `xorm:"-"`
Repo *Repository `xorm:"-"`
}


+ 1
- 0
models/models.go View File

@@ -128,6 +128,7 @@ func init() {
new(Dataset), new(Dataset),
new(Cloudbrain), new(Cloudbrain),
new(FileChunk), new(FileChunk),
new(BlockChain),
) )


gonicNames := []string{"SSL", "UID"} gonicNames := []string{"SSL", "UID"}


+ 10
- 0
models/repo.go View File

@@ -6,6 +6,7 @@
package models package models


import ( import (
"code.gitea.io/gitea/modules/blockchain"
"context" "context"
"crypto/md5" "crypto/md5"
"errors" "errors"
@@ -195,6 +196,10 @@ type Repository struct {
// Avatar: ID(10-20)-md5(32) - must fit into 64 symbols // Avatar: ID(10-20)-md5(32) - must fit into 64 symbols
Avatar string `xorm:"VARCHAR(64)"` Avatar string `xorm:"VARCHAR(64)"`


//blockchain
ContractAddress string `xorm:"INDEX"`
Balance int64 `xorm:"NOT NULL DEFAULT 0"`

CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
} }
@@ -1051,6 +1056,11 @@ func CreateRepository(ctx DBContext, doer, u *User, repo *Repository) (err error
return err return err
} }


_, err = blockchain.NewRepo(string(repo.ID), u.PublicKey, repo.Name)
if err != nil {
log.Error("newRepo failed:", err.Error())
}

// insert units for repo // insert units for repo
var units = make([]RepoUnit, 0, len(DefaultRepoUnits)) var units = make([]RepoUnit, 0, len(DefaultRepoUnits))
for _, tp := range DefaultRepoUnits { for _, tp := range DefaultRepoUnits {


+ 16
- 1
models/user.go View File

@@ -6,6 +6,7 @@
package models package models


import ( import (
"code.gitea.io/gitea/modules/blockchain"
"container/list" "container/list"
"context" "context"
"crypto/md5" "crypto/md5"
@@ -35,6 +36,7 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"


"github.com/go-resty/resty/v2"
"github.com/unknwon/com" "github.com/unknwon/com"
"golang.org/x/crypto/argon2" "golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
@@ -91,6 +93,8 @@ var (


// Characters prohibited in a user name (anything except A-Za-z0-9_.-) // Characters prohibited in a user name (anything except A-Za-z0-9_.-)
alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`) alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)

restyClient *resty.Client
) )


// User represents the object of individual and member of organization. // User represents the object of individual and member of organization.
@@ -167,7 +171,10 @@ type User struct {
Theme string `xorm:"NOT NULL DEFAULT ''"` Theme string `xorm:"NOT NULL DEFAULT ''"`


//CloudBrain //CloudBrain
Token string `xorm:"VARCHAR(1024)"`
Token string `xorm:"VARCHAR(1024)"`

//BlockChain
PublicKey string `xorm`
} }


// SearchOrganizationsOptions options to filter organizations // SearchOrganizationsOptions options to filter organizations
@@ -965,6 +972,14 @@ func CreateUser(u *User) (err error) {
return err return err
} }


result, err := blockchain.CreateBlockchainAccount()
if err != nil {
log.Error("createBlockchainAccount failed:", err.Error())
return err
}

u.PublicKey = result.Payload["publickey"].(string)

sess := x.NewSession() sess := x.NewSession()
defer sess.Close() defer sess.Close()
if err = sess.Begin(); err != nil { if err = sess.Begin(); err != nil {


+ 14
- 0
modules/blockchain/blockchain.go View File

@@ -0,0 +1,14 @@
package blockchain

const (
Command = `pip3 install jupyterlab==2.2.5 -i https://pypi.tuna.tsinghua.edu.cn/simple;service ssh stop;jupyter lab --no-browser --ip=0.0.0.0 --allow-root --notebook-dir="/code" --port=80 --LabApp.token="" --LabApp.allow_origin="self https://cloudbrain.pcl.ac.cn"`
CodeMountPath = "/code"
DataSetMountPath = "/dataset"
ModelMountPath = "/model"
BenchMarkMountPath = "/benchmark"
TaskInfoName = "/taskInfo"

SubTaskName = "task1"


)

+ 145
- 0
modules/blockchain/resty.go View File

@@ -0,0 +1,145 @@
package blockchain

import (
"fmt"

"code.gitea.io/gitea/modules/setting"
"github.com/go-resty/resty/v2"
)

var (
restyClient *resty.Client
)

const (
UrlCreateAccount = "createAccount"
UrlGetBalance = "getBalance"
UrlNewRepo = "newRepo"
UrlContribute = "contribute"

Success = 0
)

type CreateAccountResult struct {
Code int `json:"code"`
Msg string `json:"message"`
Payload map[string]interface{} `json:"data"`
}

type GetBalanceResult struct {
Code int `json:"code"`
Msg string `json:"message"`
Payload map[string]interface{} `json:"data"`
}

type NewRepoResult struct {
Code int `json:"code"`
Msg string `json:"message"`
Data string `json:"data"`
}

type ContributeResult struct {
Code int `json:"code"`
Msg string `json:"message"`
Payload map[string]interface{} `json:"data"`
}

func getRestyClient() *resty.Client {
if restyClient == nil {
restyClient = resty.New()
}
return restyClient
}

func CreateBlockchainAccount() (*CreateAccountResult, error) {
client := getRestyClient()
var result CreateAccountResult

res, err := client.R().
SetHeader("Content-Type", "application/json").
SetResult(&result).
Get(setting.BlockChainHost + UrlCreateAccount)

if err != nil {
return nil, fmt.Errorf("resty create account: %s", err)
}

if result.Code != Success {
return &result, fmt.Errorf("CreateAccount err: %s", res.String())
}

return &result, nil
}

func NewRepo(repoID, publicKey, repoName string) (*NewRepoResult, error) {
client := getRestyClient()
var result NewRepoResult

res, err := client.R().
SetHeader("Accept", "application/json").
SetQueryParams(map[string]string{
"repoId" : repoID,
"creator" : publicKey,
"repoName" : repoName,
}).
SetResult(&result).
Get(setting.BlockChainHost + UrlNewRepo)

if err != nil {
return nil, fmt.Errorf("resty newRepo: %v", err)
}

if result.Code != Success {
return &result, fmt.Errorf("newRepo err: %s", res.String())
}

return &result, nil
}

func GetBalance(contractAddress, contributor string) (*GetBalanceResult, error) {
client := getRestyClient()
var result GetBalanceResult

res, err := client.R().
SetHeader("Accept", "application/json").
SetQueryParams(map[string]string{
"contractAddress" : contractAddress,
"contributor" : contributor,
}).
SetResult(&result).
Get(setting.BlockChainHost + UrlGetBalance)

if err != nil {
return nil, fmt.Errorf("resty getBalance: %v", err)
}

if result.Code != Success {
return &result, fmt.Errorf("getBalance err: %s", res.String())
}

return &result, nil
}

func Contribute(jobID string) (*ContributeResult, error) {
client := getRestyClient()
var result ContributeResult

res, err := client.R().
SetHeader("Accept", "application/json").
SetQueryParams(map[string]string{
"contractAddress" : "",
"contributor" : "",
}).
SetResult(&result).
Get(setting.BlockChainHost + UrlContribute)

if err != nil {
return nil, fmt.Errorf("resty contribute: %v", err)
}

if result.Code != Success {
return &result, fmt.Errorf("contribute err: %s", res.String())
}

return &result, nil
}

+ 6
- 0
modules/setting/setting.go View File

@@ -443,6 +443,9 @@ var (
IsBenchmarkEnabled bool IsBenchmarkEnabled bool
BenchmarkCode string BenchmarkCode string
BenchmarkServerHost string BenchmarkServerHost string

//blockchain config
BlockChainHost string
) )


// DateLang transforms standard language locale name to corresponding value in datetime plugin. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
@@ -1123,6 +1126,9 @@ func NewContext() {
IsBenchmarkEnabled = sec.Key("ENABLED").MustBool(false) IsBenchmarkEnabled = sec.Key("ENABLED").MustBool(false)
BenchmarkCode = sec.Key("BENCHMARKCODE").MustString("https://yangzhx:justfortest123@git.openi.org.cn/yangzhx/detection_benchmark_script.git") BenchmarkCode = sec.Key("BENCHMARKCODE").MustString("https://yangzhx:justfortest123@git.openi.org.cn/yangzhx/detection_benchmark_script.git")
BenchmarkServerHost = sec.Key("HOST").MustString("http://192.168.202.90:3366/") BenchmarkServerHost = sec.Key("HOST").MustString("http://192.168.202.90:3366/")

sec = Cfg.Section("blockchain")
BlockChainHost = sec.Key("HOST").MustString("http://192.168.136.66:3302/")
} }


func loadInternalToken(sec *ini.Section) string { func loadInternalToken(sec *ini.Section) string {


+ 1
- 1
modules/worker/task.go View File

@@ -14,7 +14,7 @@ const (
) )


func SendDecompressTask(ctx context.Context, uuid string) error { func SendDecompressTask(ctx context.Context, uuid string) error {
args := []tasks.Arg{{Name: "uuid", Type: "string", Value: uuid}}
args := []tasks.Arg{{Name: "uuid", Type: "string", Value: uuid},{}}
task, err := tasks.NewSignature(DecompressTaskName, args) task, err := tasks.NewSignature(DecompressTaskName, args)
if err != nil { if err != nil {
log.Error("NewSignature failed:", err.Error()) log.Error("NewSignature failed:", err.Error())


Loading…
Cancel
Save