<commit_before>// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package gce

import (
	"code.google.com/p/google-api-go-client/compute/v1"
	"github.com/juju/errors"

	"github.com/juju/juju/instance"
	"github.com/juju/juju/network"
)

type environInstance struct {
	id        instance.Id
	env       *environ
	projectID string
	zone      string

	gce *compute.Instance
}

var _ instance.Instance = (*environInstance)(nil)

func (inst *environInstance) getInstance() *compute.Instance {
	return inst.gce
}

func (inst *environInstance) Id() instance.Id {
	return inst.id
}

func (inst *environInstance) Status() string {
	return inst.gce.Status
}

func (inst *environInstance) Refresh() error {
	env := inst.env.getSnapshot()

	// TODO(ericsnow) is zone the right thing
	call := env.gce.Instances.Get(env.projectID, inst.zone, string(inst.id))
	gInst, err := call.Do()
	if err != nil {
		return errors.Trace(err)
	}
	inst.gce = gInst
	inst.projectID = env.projectID
	return nil
}

func (inst *environInstance) Addresses() ([]network.Address, error) {
	var addresses []network.Address

	for _, netif := range inst.gce.NetworkInterfaces {
		// Add public addresses.
		for _, accessConfig := range netif.AccessConfigs {
			if accessConfig.NatIP == "" {
				continue
			}
			address := network.Address{
				Value: accessConfig.NatIP,
				Type:  network.IPv4Address,
				Scope: network.ScopePublic,
			}
			addresses = append(addresses, address)

		}

		// Add private address.
		// TODO(ericsnow) Are these really the internal addresses?
		if netif.NetworkIP == "" {
			continue
		}
		address := network.Address{
			Value: netif.NetworkIP,
			Type:  network.IPv4Address,
			Scope: network.ScopeCloudLocal,
		}
		addresses = append(addresses, address)
	}

	return addresses, nil
}

// firewall stuff

func (inst *environInstance) waitOperation(operation *compute.Operation) error {
	return errNotImplemented
}

// buildFirewall expands a port range set in to compute.FirewallAllowed and returns
// a compute.Firewall for the machineId.
func buildFirewall(machineId string, ps network.PortSet) *compute.Firewall {
	firewall := compute.Firewall{
		// Allowed is set below.
		// Description is not set.
		Name: machineId,
		// TODO(ericsnow) Does Network need to be set?
		Network: "",
		// SourceRanges is not set.
		// SourceTags is not set.
		// TargetTags is not set.
	}

	for _, protocol := range ps.Protocols() {
		allowed := compute.FirewallAllowed{
			IPProtocol: protocol,
			Ports:      ps.PortStrings(protocol),
		}
		firewall.Allowed = append(firewall.Allowed, &allowed)
	}
	return &firewall
}

// OpenPorts opens the given ports on the instance, which
// should have been started with the given machine id.
func (inst *environInstance) OpenPorts(machineId string, ports []network.PortRange) error {
	// Compose the full set of open ports.
	currentPorts, err := inst.Ports(machineId)
	if err != nil {
		return errors.Trace(err)
	}
	inputPortsSet := network.NewPortSet(ports...)
	if inputPortsSet.IsEmpty() {
		return nil
	}
	currentPortsSet := network.NewPortSet(currentPorts...)

	// Send the request, depending on the current ports.
	var operation *compute.Operation
	env := inst.env.getSnapshot()
	if currentPortsSet.IsEmpty() {
		firewall := buildFirewall(machineId, inputPortsSet)
		call := env.gce.Firewalls.Insert(inst.projectID, firewall)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}

	} else {
		newPortsSet := currentPortsSet.Union(inputPortsSet)
		firewall := buildFirewall(machineId, newPortsSet)
		call := env.gce.Firewalls.Update(inst.projectID, machineId, firewall)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}
	}

	if err := inst.waitOperation(operation); err != nil {
		return errors.Annotatef(err, "opening port(s) %+v", ports)
	}

	return nil
}

// ClosePorts closes the given ports on the instance, which
// should have been started with the given machine id.
func (inst *environInstance) ClosePorts(machineId string, ports []network.PortRange) error {
	// Compose the full set of open ports.
	currentPorts, err := inst.Ports(machineId)
	if err != nil {
		return errors.Trace(err)
	}
	inputPortsSet := network.NewPortSet(ports...)
	if inputPortsSet.IsEmpty() {
		return nil
	}
	currentPortsSet := network.NewPortSet(currentPorts...)
	newPortsSet := currentPortsSet.Difference(inputPortsSet)

	// Send the request, depending on the current ports.
	var operation *compute.Operation
	env := inst.env.getSnapshot()
	if newPortsSet.IsEmpty() {
		call := env.gce.Firewalls.Delete(inst.projectID, machineId)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}
	} else {
		firewall := buildFirewall(machineId, newPortsSet)
		call := env.gce.Firewalls.Update(inst.projectID, machineId, firewall)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}
	}

	if err := inst.waitOperation(operation); err != nil {
		return errors.Annotatef(err, "opening port(s) %+v", ports)
	}

	return nil
}

// Ports returns the set of ports open on the instance, which
// should have been started with the given machine id.
// The ports are returned as sorted by SortPorts.
func (inst *environInstance) Ports(machineId string) ([]network.PortRange, error) {
	env := inst.env.getSnapshot()
	call := env.gce.Firewalls.Get(inst.projectID, machineId)
	firewall, err := call.Do()
	if err != nil {
		return nil, errors.Annotate(err, "while getting ports from GCE")
	}

	var ports []network.PortRange
	for _, allowed := range firewall.Allowed {
		for _, portRangeStr := range allowed.Ports {
			portRange, err := network.ParsePortRangePorts(portRangeStr, allowed.IPProtocol)
			if err != nil {
				return ports, errors.Annotate(err, "bad ports from GCE")
			}
			ports = append(ports, portRange)
		}
	}

	return ports, nil
}
<commit_msg>Do not set Network in the firewall by default.<commit_after>// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package gce

import (
	"code.google.com/p/google-api-go-client/compute/v1"
	"github.com/juju/errors"

	"github.com/juju/juju/instance"
	"github.com/juju/juju/network"
)

type environInstance struct {
	id        instance.Id
	env       *environ
	projectID string
	zone      string

	gce *compute.Instance
}

var _ instance.Instance = (*environInstance)(nil)

func (inst *environInstance) getInstance() *compute.Instance {
	return inst.gce
}

func (inst *environInstance) Id() instance.Id {
	return inst.id
}

func (inst *environInstance) Status() string {
	return inst.gce.Status
}

func (inst *environInstance) Refresh() error {
	env := inst.env.getSnapshot()

	// TODO(ericsnow) is zone the right thing
	call := env.gce.Instances.Get(env.projectID, inst.zone, string(inst.id))
	gInst, err := call.Do()
	if err != nil {
		return errors.Trace(err)
	}
	inst.gce = gInst
	inst.projectID = env.projectID
	return nil
}

func (inst *environInstance) Addresses() ([]network.Address, error) {
	var addresses []network.Address

	for _, netif := range inst.gce.NetworkInterfaces {
		// Add public addresses.
		for _, accessConfig := range netif.AccessConfigs {
			if accessConfig.NatIP == "" {
				continue
			}
			address := network.Address{
				Value: accessConfig.NatIP,
				Type:  network.IPv4Address,
				Scope: network.ScopePublic,
			}
			addresses = append(addresses, address)

		}

		// Add private address.
		// TODO(ericsnow) Are these really the internal addresses?
		if netif.NetworkIP == "" {
			continue
		}
		address := network.Address{
			Value: netif.NetworkIP,
			Type:  network.IPv4Address,
			Scope: network.ScopeCloudLocal,
		}
		addresses = append(addresses, address)
	}

	return addresses, nil
}

// firewall stuff

func (inst *environInstance) waitOperation(operation *compute.Operation) error {
	return errNotImplemented
}

// buildFirewall expands a port range set in to compute.FirewallAllowed and returns
// a compute.Firewall for the machineId.
func buildFirewall(machineId string, ps network.PortSet) *compute.Firewall {
	firewall := compute.Firewall{
		// Allowed is set below.
		// Description is not set.
		Name: machineId,
		// TODO(ericsnow) Does Network need to be set?
		// Network: "",
		// SourceRanges is not set.
		// SourceTags is not set.
		// TargetTags is not set.
	}

	for _, protocol := range ps.Protocols() {
		allowed := compute.FirewallAllowed{
			IPProtocol: protocol,
			Ports:      ps.PortStrings(protocol),
		}
		firewall.Allowed = append(firewall.Allowed, &allowed)
	}
	return &firewall
}

// OpenPorts opens the given ports on the instance, which
// should have been started with the given machine id.
func (inst *environInstance) OpenPorts(machineId string, ports []network.PortRange) error {
	// Compose the full set of open ports.
	currentPorts, err := inst.Ports(machineId)
	if err != nil {
		return errors.Trace(err)
	}
	inputPortsSet := network.NewPortSet(ports...)
	if inputPortsSet.IsEmpty() {
		return nil
	}
	currentPortsSet := network.NewPortSet(currentPorts...)

	// Send the request, depending on the current ports.
	var operation *compute.Operation
	env := inst.env.getSnapshot()
	if currentPortsSet.IsEmpty() {
		firewall := buildFirewall(machineId, inputPortsSet)
		call := env.gce.Firewalls.Insert(inst.projectID, firewall)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}

	} else {
		newPortsSet := currentPortsSet.Union(inputPortsSet)
		firewall := buildFirewall(machineId, newPortsSet)
		call := env.gce.Firewalls.Update(inst.projectID, machineId, firewall)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}
	}

	if err := inst.waitOperation(operation); err != nil {
		return errors.Annotatef(err, "opening port(s) %+v", ports)
	}

	return nil
}

// ClosePorts closes the given ports on the instance, which
// should have been started with the given machine id.
func (inst *environInstance) ClosePorts(machineId string, ports []network.PortRange) error {
	// Compose the full set of open ports.
	currentPorts, err := inst.Ports(machineId)
	if err != nil {
		return errors.Trace(err)
	}
	inputPortsSet := network.NewPortSet(ports...)
	if inputPortsSet.IsEmpty() {
		return nil
	}
	currentPortsSet := network.NewPortSet(currentPorts...)
	newPortsSet := currentPortsSet.Difference(inputPortsSet)

	// Send the request, depending on the current ports.
	var operation *compute.Operation
	env := inst.env.getSnapshot()
	if newPortsSet.IsEmpty() {
		call := env.gce.Firewalls.Delete(inst.projectID, machineId)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}
	} else {
		firewall := buildFirewall(machineId, newPortsSet)
		call := env.gce.Firewalls.Update(inst.projectID, machineId, firewall)
		operation, err = call.Do()
		if err != nil {
			return errors.Trace(err)
		}
	}

	if err := inst.waitOperation(operation); err != nil {
		return errors.Annotatef(err, "opening port(s) %+v", ports)
	}

	return nil
}

// Ports returns the set of ports open on the instance, which
// should have been started with the given machine id.
// The ports are returned as sorted by SortPorts.
func (inst *environInstance) Ports(machineId string) ([]network.PortRange, error) {
	env := inst.env.getSnapshot()
	call := env.gce.Firewalls.Get(inst.projectID, machineId)
	firewall, err := call.Do()
	if err != nil {
		return nil, errors.Annotate(err, "while getting ports from GCE")
	}

	var ports []network.PortRange
	for _, allowed := range firewall.Allowed {
		for _, portRangeStr := range allowed.Ports {
			portRange, err := network.ParsePortRangePorts(portRangeStr, allowed.IPProtocol)
			if err != nil {
				return ports, errors.Annotate(err, "bad ports from GCE")
			}
			ports = append(ports, portRange)
		}
	}

	return ports, nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"go/build"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/robfig/revel"
)

var cmdNew = &Command{
	UsageLine: "new [path] [skeleton]",
	Short:     "create a skeleton Revel application",
	Long: `
New creates a few files to get a new Revel application running quickly.

It puts all of the files in the given import path, taking the final element in
the path to be the app name.

Skeleton is an optional argument, provided as an import path

For example:

    revel new import/path/helloworld

    revel new import/path/helloworld import/path/skeleton
`,
}

func init() {
	cmdNew.Run = newApp
}

var (

	// go related paths
	gopath  string
	gocmd   string
	srcRoot string

	// revel related paths
	revelPkg     *build.Package
	appPath      string
	appName      string
	basePath     string
	importPath   string
	skeletonPath string
)

func newApp(args []string) {
	// check for proper args by count
	if len(args) == 0 {
		errorf("No import path given.\nRun 'revel help new' for usage.\n")
	}
	if len(args) > 2 {
		errorf("Too many arguments provided.\nRun 'revel help new' for usage.\n")
	}

	// checking and setting application
	setApplicationPath(args)

	// checking and setting skeleton
	setSkeletonPath(args)

	// copy files to new app directory
	copyNewAppFiles()

	// goodbye world
	fmt.Fprintln(os.Stdout, "Your application is ready:\n  ", appPath)
	fmt.Fprintln(os.Stdout, "\nYou can run it with:\n   revel run", importPath)
}

const alphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func generateSecret() string {
	chars := make([]byte, 64)
	for i := 0; i < 64; i++ {
		chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))]
	}
	return string(chars)
}

// lookup and set Go related variables
func initGoStuff() {
	// lookup go path
	gopath = build.Default.GOPATH
	if gopath == "" {
		errorf("Abort: GOPATH environment variable is not set. " +
			"Please refer to http://golang.org/doc/code.html to configure your Go environment.")
	}

	// set go src path
	srcRoot = filepath.Join(filepath.SplitList(gopath)[0], "src")

	// check for go executable
	var err error
	gocmd, err = exec.LookPath("go")
	if err != nil {
		errorf("Go executable not found in PATH.")
	}

}

func setApplicationPath(args []string) {
	var err error
	importPath = args[0]
	if filepath.IsAbs(importPath) {
		errorf("Abort: '%s' looks like a directory.  Please provide a Go import path instead.",
			importPath)
	}

	_, err = build.Import(importPath, "", build.FindOnly)
	if err == nil {
		errorf("Abort: Import path %s already exists.\n", importPath)
	}

	revelPkg, err = build.Import(revel.REVEL_IMPORT_PATH, "", build.FindOnly)
	if err != nil {
		errorf("Abort: Could not find Revel source code: %s\n", err)
	}

	appPath = filepath.Join(srcRoot, filepath.FromSlash(importPath))
	appName = filepath.Base(appPath)
	basePath = filepath.Dir(appPath)
	if basePath == "." {
		basePath = ""
	} else {
		basePath += "/"
	}
}

func setSkeletonPath(args []string) {
	var err error
	if len(args) == 2 { // user specified
		skeletonName := args[1]
		_, err = build.Import(skeletonName, "", build.FindOnly)
		if err != nil {
			// Execute "go get <pkg>"
			getCmd := exec.Command(gocmd, "get", "-d", skeletonName)
			fmt.Println("Exec:", getCmd.Args)
			getOutput, err := getCmd.CombinedOutput()

			// check getOutput for no buildible string
			bpos := bytes.Index(getOutput, []byte("no buildable Go source files in"))
			if err != nil && bpos == -1 {
				errorf("Abort: Could not find or 'go get' Skeleton  source code: %s\n%s\n", getOutput, skeletonName)
			}
		}
		// use the
		skeletonPath = filepath.Join(srcRoot, skeletonName)

	} else {
		// use the revel default
		skeletonPath = filepath.Join(revelPkg.Dir, "skeleton")
	}
}

func copyNewAppFiles() {
	var err error
	err = os.MkdirAll(appPath, 0777)
	panicOnError(err, "Failed to create directory "+appPath)

	mustCopyDir(appPath, skeletonPath, map[string]interface{}{
		// app.conf
		"AppName":  appName,
		"BasePath": basePath,
		"Secret":   generateSecret(),
	})

	// Dotfiles are skipped by mustCopyDir, so we have to explicitly copy the .gitignore.
	gitignore := ".gitignore"
	mustCopyFile(filepath.Join(appPath, gitignore), filepath.Join(skeletonPath, gitignore))

}
<commit_msg>this fixes the slash issue on windows<commit_after>package main

import (
	"bytes"
	"fmt"
	"go/build"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/robfig/revel"
)

var cmdNew = &Command{
	UsageLine: "new [path] [skeleton]",
	Short:     "create a skeleton Revel application",
	Long: `
New creates a few files to get a new Revel application running quickly.

It puts all of the files in the given import path, taking the final element in
the path to be the app name.

Skeleton is an optional argument, provided as an import path

For example:

    revel new import/path/helloworld

    revel new import/path/helloworld import/path/skeleton
`,
}

func init() {
	cmdNew.Run = newApp
}

var (

	// go related paths
	gopath  string
	gocmd   string
	srcRoot string

	// revel related paths
	revelPkg     *build.Package
	appPath      string
	appName      string
	basePath     string
	importPath   string
	skeletonPath string
)

func newApp(args []string) {
	// check for proper args by count
	if len(args) == 0 {
		errorf("No import path given.\nRun 'revel help new' for usage.\n")
	}
	if len(args) > 2 {
		errorf("Too many arguments provided.\nRun 'revel help new' for usage.\n")
	}

	// checking and setting application
	setApplicationPath(args)

	// checking and setting skeleton
	setSkeletonPath(args)

	// copy files to new app directory
	copyNewAppFiles()

	// goodbye world
	fmt.Fprintln(os.Stdout, "Your application is ready:\n  ", appPath)
	fmt.Fprintln(os.Stdout, "\nYou can run it with:\n   revel run", importPath)
}

const alphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

func generateSecret() string {
	chars := make([]byte, 64)
	for i := 0; i < 64; i++ {
		chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))]
	}
	return string(chars)
}

// lookup and set Go related variables
func initGoStuff() {
	// lookup go path
	gopath = build.Default.GOPATH
	if gopath == "" {
		errorf("Abort: GOPATH environment variable is not set. " +
			"Please refer to http://golang.org/doc/code.html to configure your Go environment.")
	}

	// set go src path
	srcRoot = filepath.Join(filepath.SplitList(gopath)[0], "src")

	// check for go executable
	var err error
	gocmd, err = exec.LookPath("go")
	if err != nil {
		errorf("Go executable not found in PATH.")
	}

}

func setApplicationPath(args []string) {
	var err error
	importPath = args[0]
	if filepath.IsAbs(importPath) {
		errorf("Abort: '%s' looks like a directory.  Please provide a Go import path instead.",
			importPath)
	}

	_, err = build.Import(importPath, "", build.FindOnly)
	if err == nil {
		errorf("Abort: Import path %s already exists.\n", importPath)
	}

	revelPkg, err = build.Import(revel.REVEL_IMPORT_PATH, "", build.FindOnly)
	if err != nil {
		errorf("Abort: Could not find Revel source code: %s\n", err)
	}

	appPath = filepath.Join(srcRoot, filepath.FromSlash(importPath))
	appName = filepath.Base(appPath)
	basePath = filepath.ToSlash(filepath.Dir(appPath))

	if basePath == "." {
		// we need to remove the a single '.' when
		// the app is in the $GOROOT/src directory
		basePath = ""
	} else {
		// we need to append a '/' when the app is
		// is a subdirectory such as $GOROOT/src/path/to/revelapp
		basePath += "/"
	}
	println(basePath)
}

func setSkeletonPath(args []string) {
	var err error
	if len(args) == 2 { // user specified
		skeletonName := args[1]
		_, err = build.Import(skeletonName, "", build.FindOnly)
		if err != nil {
			// Execute "go get <pkg>"
			getCmd := exec.Command(gocmd, "get", "-d", skeletonName)
			fmt.Println("Exec:", getCmd.Args)
			getOutput, err := getCmd.CombinedOutput()

			// check getOutput for no buildible string
			bpos := bytes.Index(getOutput, []byte("no buildable Go source files in"))
			if err != nil && bpos == -1 {
				errorf("Abort: Could not find or 'go get' Skeleton  source code: %s\n%s\n", getOutput, skeletonName)
			}
		}
		// use the
		skeletonPath = filepath.Join(srcRoot, skeletonName)

	} else {
		// use the revel default
		skeletonPath = filepath.Join(revelPkg.Dir, "skeleton")
	}
}

func copyNewAppFiles() {
	var err error
	err = os.MkdirAll(appPath, 0777)
	panicOnError(err, "Failed to create directory "+appPath)

	mustCopyDir(appPath, skeletonPath, map[string]interface{}{
		// app.conf
		"AppName":  appName,
		"BasePath": basePath,
		"Secret":   generateSecret(),
	})

	// Dotfiles are skipped by mustCopyDir, so we have to explicitly copy the .gitignore.
	gitignore := ".gitignore"
	mustCopyFile(filepath.Join(appPath, gitignore), filepath.Join(skeletonPath, gitignore))

}
<|endoftext|>


<commit_before>package reviewdog

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/haya14busa/reviewdog/diff"
)

// Reviewdog represents review dog application which parses result of compiler
// or linter, get diff and filter the results by diff, and report filterd
// results.
type Reviewdog struct {
	toolname string
	p        Parser
	c        CommentService
	d        DiffService
}

// NewReviewdog returns a new Reviewdog.
func NewReviewdog(toolname string, p Parser, c CommentService, d DiffService) *Reviewdog {
	return &Reviewdog{p: p, c: c, d: d, toolname: toolname}
}

// CheckResult represents a checked result of static analysis tools.
// :h error-file-format
type CheckResult struct {
	Path    string   // relative file path
	Lnum    int      // line number
	Col     int      // column number (1 <tab> == 1 character column)
	Message string   // error message
	Lines   []string // Original error lines (often one line)
}

// Parser is an interface which parses compilers, linters, or any tools
// results.
type Parser interface {
	Parse(r io.Reader) ([]*CheckResult, error)
}

// Comment represents a reported result as a comment.
type Comment struct {
	*CheckResult
	Body     string
	LnumDiff int
	ToolName string
}

// CommentService is an interface which posts Comment.
type CommentService interface {
	Post(*Comment) error
}

// DiffService is an interface which get diff.
type DiffService interface {
	Diff() ([]byte, error)
	Strip() int
}

// Run runs Reviewdog application.
func (w *Reviewdog) Run(r io.Reader) error {
	results, err := w.p.Parse(r)
	if err != nil {
		return fmt.Errorf("parse error: %v", err)
	}

	d, err := w.d.Diff()
	if err != nil {
		return fmt.Errorf("fail to get diff: %v", err)
	}

	filediffs, err := diff.ParseMultiFile(bytes.NewReader(d))
	if err != nil {
		return fmt.Errorf("fail to parse diff: %v", err)
	}
	addedlines := addedDiffLines(filediffs, w.d.Strip())

	wd, err := os.Getwd()
	if err != nil {
		return err
	}

	for _, result := range results {
		addedline := addedlines.Get(result.Path, result.Lnum)
		if filepath.IsAbs(result.Path) {
			relpath, err := filepath.Rel(wd, result.Path)
			if err != nil {
				return err
			}
			result.Path = relpath
		}
		if addedline != nil {
			comment := &Comment{
				CheckResult: result,
				Body:        result.Message, // TODO: format message
				LnumDiff:    addedline.LnumDiff,
				ToolName:    w.toolname,
			}
			if err := w.c.Post(comment); err != nil {
				return err
			}
		}
	}

	return nil
}

// AddedLine represents added line in diff.
type AddedLine struct {
	Path     string // path to new file
	Lnum     int    // the line number in the new file
	LnumDiff int    // the line number of the diff (Same as Lnumdiff of diff.Line)
	Content  string // line content
}

// posToAddedLine is a hash table of normalized path to line number to AddedLine.
type posToAddedLine map[string]map[int]*AddedLine

func (p posToAddedLine) Get(path string, lnum int) *AddedLine {
	npath, err := normalizePath(path)
	if err != nil {
		return nil
	}
	ltodiff, ok := p[npath]
	if !ok {
		return nil
	}
	diffline, ok := ltodiff[lnum]
	if !ok {
		return nil
	}
	return diffline
}

// addedDiffLines traverse []*diff.FileDiff and returns posToAddedLine.
func addedDiffLines(filediffs []*diff.FileDiff, strip int) posToAddedLine {
	r := make(posToAddedLine)
	for _, filediff := range filediffs {
		path := filediff.PathNew
		ltodiff := make(map[int]*AddedLine)
		ps := strings.Split(filepath.ToSlash(filediff.PathNew), "/")

		if len(ps) > strip {
			path = filepath.Join(ps[strip:]...)
		}
		np, err := normalizePath(path)
		if err != nil {
			// FIXME(haya14busa): log or return error?
			continue
		}
		path = np

		for _, hunk := range filediff.Hunks {
			for _, line := range hunk.Lines {
				if line.Type == diff.LineAdded {
					ltodiff[line.LnumNew] = &AddedLine{
						Path:     path,
						Lnum:     line.LnumNew,
						LnumDiff: line.LnumDiff,
						Content:  line.Content,
					}
				}
			}
		}
		r[path] = ltodiff
	}
	return r
}

func normalizePath(p string) (string, error) {
	path, err := filepath.Abs(p)
	if err != nil {
		return "", err
	}
	return filepath.ToSlash(path), nil
}
<commit_msg>[revert later] add stupid code intentionally<commit_after>package reviewdog

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/haya14busa/reviewdog/diff"
)

var unusedVar = 1

// Reviewdog represents review dog application which parses result of compiler
// or linter, get diff and filter the results by diff, and report filterd
// results.
type Reviewdog struct {
	toolname string
	p        Parser
	c        CommentService
	d        DiffService
}

// NewReviewdog returns a new Reviewdog.
func NewReviewdog(toolname string, p Parser, c CommentService, d DiffService) *Reviewdog {
	return &Reviewdog{p: p, c: c, d: d, toolname: toolname}
}

// CheckResult represents a checked result of static analysis tools.
// :h error-file-format
type CheckResult struct {
	Path    string   // relative file path
	Lnum    int      // line number
	Col     int      // column number (1 <tab> == 1 character column)
	Message string   // error message
	Lines   []string // Original error lines (often one line)
}

// Parser is an interface which parses compilers, linters, or any tools
// results.
type Parser interface {
	Parse(r io.Reader) ([]*CheckResult, error)
}

// Comment represents a reported result as a comment.
type Comment struct {
	*CheckResult
	Body     string
	LnumDiff int
	ToolName string
}

// CommentService is an interface which posts Comment.
type CommentService interface {
	Post(*Comment) error
}

// DiffService is an interface which get diff.
type DiffService interface {
	Diff() ([]byte, error)
	Strip() int
}

// Run runs Reviewdog application.
func (w *Reviewdog) Run(r io.Reader) error {
	results, err := w.p.Parse(r)
	if err != nil {
		return fmt.Errorf("parse error: %v", err)
	}

	d, err := w.d.Diff()
	if err != nil {
		return fmt.Errorf("fail to get diff: %v", err)
	}

	filediffs, err := diff.ParseMultiFile(bytes.NewReader(d))
	if err != nil {
		return fmt.Errorf("fail to parse diff: %v", err)
	}
	addedlines := addedDiffLines(filediffs, w.d.Strip())

	wd, err := os.Getwd()
	if err != nil {
		return err
	}

	for _, result := range results {
		addedline := addedlines.Get(result.Path, result.Lnum)
		if filepath.IsAbs(result.Path) {
			relpath, err := filepath.Rel(wd, result.Path)
			if err != nil {
				return err
			}
			result.Path = relpath
		}
		if addedline != nil {
			comment := &Comment{
				CheckResult: result,
				Body:        result.Message, // TODO: format message
				LnumDiff:    addedline.LnumDiff,
				ToolName:    w.toolname,
			}
			if err := w.c.Post(comment); err != nil {
				return err
			}
		}
	}

	return nil
}

// AddedLine represents added line in diff.
type AddedLine struct {
	Path     string // path to new file
	Lnum     int    // the line number in the new file
	LnumDiff int    // the line number of the diff (Same as Lnumdiff of diff.Line)
	Content  string // line content
}

// posToAddedLine is a hash table of normalized path to line number to AddedLine.
type posToAddedLine map[string]map[int]*AddedLine

func (p posToAddedLine) Get(path string, lnum int) *AddedLine {
	npath, err := normalizePath(path)
	if err != nil {
		return nil
	}
	ltodiff, ok := p[npath]
	if !ok {
		return nil
	}
	diffline, ok := ltodiff[lnum]
	if !ok {
		return nil
	}
	return diffline
}

// addedDiffLines traverse []*diff.FileDiff and returns posToAddedLine.
func addedDiffLines(filediffs []*diff.FileDiff, strip int) posToAddedLine {
	r := make(posToAddedLine)
	for _, filediff := range filediffs {
		path := filediff.PathNew
		ltodiff := make(map[int]*AddedLine)
		ps := strings.Split(filepath.ToSlash(filediff.PathNew), "/")

		if len(ps) > strip {
			path = filepath.Join(ps[strip:]...)
		}
		np, err := normalizePath(path)
		if err != nil {
			// FIXME(haya14busa): log or return error?
			continue
		}
		path = np

		for _, hunk := range filediff.Hunks {
			for _, line := range hunk.Lines {
				if line.Type == diff.LineAdded {
					ltodiff[line.LnumNew] = &AddedLine{
						Path:     path,
						Lnum:     line.LnumNew,
						LnumDiff: line.LnumDiff,
						Content:  line.Content,
					}
				}
			}
		}
		r[path] = ltodiff
	}
	return r
}

func normalizePath(p string) (string, error) {
	path, err := filepath.Abs(p)
	if err != nil {
		return "", err
	}
	return filepath.ToSlash(path), nil
}
<|endoftext|>


<commit_before>package main

import (
	"../libs/twodee"
)

type ItemType int
type ItemId int

// Corresponds with frame indices
const (
	_               = iota
	ItemDown ItemId = iota
	ItemUp
	Item1
	Item2
	Item3
	Item4
	ItemFinal
	ItemPump
	ItemPickaxe
	ItemRock
	item_sentinel
)

// Various item types
const (
	LayerThresholdItem ItemType = iota
	InventoryItem
	UseableItem
	DestructableItem
)

var ItemIdToType = map[ItemId]ItemType{
	ItemDown:    LayerThresholdItem,
	ItemUp:      LayerThresholdItem,
	Item1:       InventoryItem,
	Item2:       InventoryItem,
	Item3:       InventoryItem,
	Item4:       InventoryItem,
	ItemFinal:   InventoryItem,
	ItemPump:    UseableItem,
	ItemPickaxe: InventoryItem,
	ItemRock:    DestructableItem,
}

const (
	NumberOfItemTypes = int(item_sentinel)
)

type Item struct {
	*twodee.BaseEntity
	Id   ItemId
	Type ItemType
	Name string
}

func NewItem(itemId ItemId, itemType ItemType, name string, x, y, w, h float32) (item *Item) {
	item = &Item{
		BaseEntity: twodee.NewBaseEntity(x, y, w, h, 0, int(itemId)),
		Id:         itemId,
		Type:       itemType,
		Name:       name,
	}
	return
}

func (i *Item) getType() ItemType {
	return i.Type
}
<commit_msg>Be specific about which item id the pump corresponds to in the entity map.<commit_after>package main

import (
	"../libs/twodee"
)

type ItemType int
type ItemId int

// Corresponds with frame indices
const (
	_               = iota
	ItemDown ItemId = iota
	ItemUp
	Item1
	Item2
	Item3
	Item4
	ItemFinal
	ItemPump    ItemId = 44
	ItemPickaxe ItemId = iota
	ItemRock
	item_sentinel
)

// Various item types
const (
	LayerThresholdItem ItemType = iota
	InventoryItem
	UseableItem
	DestructableItem
)

var ItemIdToType = map[ItemId]ItemType{
	ItemDown:    LayerThresholdItem,
	ItemUp:      LayerThresholdItem,
	Item1:       InventoryItem,
	Item2:       InventoryItem,
	Item3:       InventoryItem,
	Item4:       InventoryItem,
	ItemFinal:   InventoryItem,
	ItemPump:    UseableItem,
	ItemPickaxe: InventoryItem,
	ItemRock:    DestructableItem,
}

const (
	NumberOfItemTypes = int(item_sentinel)
)

type Item struct {
	*twodee.BaseEntity
	Id   ItemId
	Type ItemType
	Name string
}

func NewItem(itemId ItemId, itemType ItemType, name string, x, y, w, h float32) (item *Item) {
	item = &Item{
		BaseEntity: twodee.NewBaseEntity(x, y, w, h, 0, int(itemId)),
		Id:         itemId,
		Type:       itemType,
		Name:       name,
	}
	return
}

func (i *Item) getType() ItemType {
	return i.Type
}
<|endoftext|>


<commit_before>package render

import (
	"strings"

	"github.com/weaveworks/scope/probe/endpoint"
	"github.com/weaveworks/scope/report"
)

// Constants are used in the tests.
const (
	IncomingInternetID = "in-theinternet"
	OutgoingInternetID = "out-theinternet"
)

// IsInternetNode determines whether the node represents the Internet.
func IsInternetNode(n report.Node) bool {
	return n.ID == IncomingInternetID || n.ID == OutgoingInternetID
}

// MakePseudoNodeID joins the parts of an id into the id of a pseudonode
func MakePseudoNodeID(parts ...string) string {
	return strings.Join(append([]string{"pseudo"}, parts...), ":")
}

// MakeGroupNodeTopology joins the parts of a group topology into the topology of a group node
func MakeGroupNodeTopology(originalTopology, key string) string {
	return strings.Join([]string{"group", originalTopology, key}, ":")
}

// NewDerivedNode makes a node based on node, but with a new ID
func NewDerivedNode(id string, node report.Node) report.Node {
	return report.MakeNode(id).WithChildren(node.Children.Add(node))
}

// NewDerivedPseudoNode makes a new pseudo node with the node as a child
func NewDerivedPseudoNode(id string, node report.Node) report.Node {
	output := NewDerivedNode(id, node).WithTopology(Pseudo)
	return output
}

func newPseudoNode(id string) report.Node {
	return report.MakeNode(id).WithTopology(Pseudo)
}

func pseudoNodeID(n report.Node, local report.Networks) (string, bool) {
	_, addr, _, ok := report.ParseEndpointNodeID(n.ID)
	if !ok {
		return "", false
	}

	if id, ok := externalNodeID(n, addr, local); ok {
		return id, ok
	}

	// due to https://github.com/weaveworks/scope/issues/1323 we are dropping
	// all non-external pseudo nodes for now.
	return "", false
}

// figure out if a node should be considered external and returns an ID which can be used to create a pseudo node
func externalNodeID(n report.Node, addr string, local report.Networks) (string, bool) {
	// First, check if it's a known service and emit a a specific node if it
	// is. This needs to be done before checking IPs since known services can
	// live in the same network, see https://github.com/weaveworks/scope/issues/2163
	if hostname, found := DNSFirstMatch(n, isKnownService); found {
		return ServiceNodeIDPrefix + hostname, true
	}

	// If the dstNodeAddr is not in a network local to this report, we emit an
	// internet pseudoNode
	// Create a buffer on the stack of this function, so we don't need to allocate in ParseIP
	var into [5]byte // one extra byte to save a memory allocation in critbitgo
	if ip := report.ParseIP([]byte(addr), into[:4]); ip != nil && !local.Contains(ip) {
		// emit one internet node for incoming, one for outgoing
		if len(n.Adjacency) > 0 {
			return IncomingInternetID, true
		}
		return OutgoingInternetID, true
	}

	// The node is not external
	return "", false
}

// DNSFirstMatch returns the first DNS name where match() returns
// true, from a prioritized list of snooped and reverse-resolved DNS
// names associated with node n.
func DNSFirstMatch(n report.Node, match func(name string) bool) (string, bool) {
	// we rely on Sets being sorted, to make selection for display more
	// deterministic
	// prioritize snooped names
	snoopedNames, _ := n.Sets.Lookup(endpoint.SnoopedDNSNames)
	for _, hostname := range snoopedNames {
		if match(hostname) {
			return hostname, true
		}
	}
	reverseNames, _ := n.Sets.Lookup(endpoint.ReverseDNSNames)
	for _, hostname := range reverseNames {
		if match(hostname) {
			return hostname, true
		}
	}
	return "", false
}
<commit_msg>introduce ParsePseudoNodeID<commit_after>package render

import (
	"strings"

	"github.com/weaveworks/scope/probe/endpoint"
	"github.com/weaveworks/scope/report"
)

// Constants are used in the tests.
const (
	IncomingInternetID = "in-theinternet"
	OutgoingInternetID = "out-theinternet"
)

// IsInternetNode determines whether the node represents the Internet.
func IsInternetNode(n report.Node) bool {
	return n.ID == IncomingInternetID || n.ID == OutgoingInternetID
}

// MakePseudoNodeID joins the parts of an id into the id of a pseudonode
func MakePseudoNodeID(parts ...string) string {
	return strings.Join(append([]string{"pseudo"}, parts...), ":")
}

// ParsePseudoNodeID returns the joined id parts of a pseudonode
// ID. If the ID is not recognisable as a pseudonode ID, it is
// returned as is, with the returned bool set to false. That is
// convenient because not all pseudonode IDs actually follow the
// format produced by MakePseudoNodeID.
func ParsePseudoNodeID(nodeID string) (string, bool) {
	// Not using strings.SplitN() to avoid a heap allocation
	pos := strings.Index(nodeID, ":")
	if pos == -1 || nodeID[:pos] != "pseudo" {
		return nodeID, false
	}
	return nodeID[pos+1:], true
}

// MakeGroupNodeTopology joins the parts of a group topology into the topology of a group node
func MakeGroupNodeTopology(originalTopology, key string) string {
	return strings.Join([]string{"group", originalTopology, key}, ":")
}

// NewDerivedNode makes a node based on node, but with a new ID
func NewDerivedNode(id string, node report.Node) report.Node {
	return report.MakeNode(id).WithChildren(node.Children.Add(node))
}

// NewDerivedPseudoNode makes a new pseudo node with the node as a child
func NewDerivedPseudoNode(id string, node report.Node) report.Node {
	output := NewDerivedNode(id, node).WithTopology(Pseudo)
	return output
}

func newPseudoNode(id string) report.Node {
	return report.MakeNode(id).WithTopology(Pseudo)
}

func pseudoNodeID(n report.Node, local report.Networks) (string, bool) {
	_, addr, _, ok := report.ParseEndpointNodeID(n.ID)
	if !ok {
		return "", false
	}

	if id, ok := externalNodeID(n, addr, local); ok {
		return id, ok
	}

	// due to https://github.com/weaveworks/scope/issues/1323 we are dropping
	// all non-external pseudo nodes for now.
	return "", false
}

// figure out if a node should be considered external and returns an ID which can be used to create a pseudo node
func externalNodeID(n report.Node, addr string, local report.Networks) (string, bool) {
	// First, check if it's a known service and emit a a specific node if it
	// is. This needs to be done before checking IPs since known services can
	// live in the same network, see https://github.com/weaveworks/scope/issues/2163
	if hostname, found := DNSFirstMatch(n, isKnownService); found {
		return ServiceNodeIDPrefix + hostname, true
	}

	// If the dstNodeAddr is not in a network local to this report, we emit an
	// internet pseudoNode
	// Create a buffer on the stack of this function, so we don't need to allocate in ParseIP
	var into [5]byte // one extra byte to save a memory allocation in critbitgo
	if ip := report.ParseIP([]byte(addr), into[:4]); ip != nil && !local.Contains(ip) {
		// emit one internet node for incoming, one for outgoing
		if len(n.Adjacency) > 0 {
			return IncomingInternetID, true
		}
		return OutgoingInternetID, true
	}

	// The node is not external
	return "", false
}

// DNSFirstMatch returns the first DNS name where match() returns
// true, from a prioritized list of snooped and reverse-resolved DNS
// names associated with node n.
func DNSFirstMatch(n report.Node, match func(name string) bool) (string, bool) {
	// we rely on Sets being sorted, to make selection for display more
	// deterministic
	// prioritize snooped names
	snoopedNames, _ := n.Sets.Lookup(endpoint.SnoopedDNSNames)
	for _, hostname := range snoopedNames {
		if match(hostname) {
			return hostname, true
		}
	}
	reverseNames, _ := n.Sets.Lookup(endpoint.ReverseDNSNames)
	for _, hostname := range reverseNames {
		if match(hostname) {
			return hostname, true
		}
	}
	return "", false
}
<|endoftext|>


<commit_before>package repl

import (
	"fmt"

	"github.com/gocql/gocql"
	"github.com/gocql/gocqlsh/metadata"

	"github.com/chzyer/readline"
	"github.com/logrusorgru/aurora"
	"github.com/olekukonko/tablewriter"
)

type CQL struct {
	db   *gocql.Session
	r    *readline.Instance
	meta *metadata.Cassandra
}

func New(db *gocql.Session, r *readline.Instance) *CQL {
	// TODO: protbably want to pass this in for testing
	r.Config.AutoComplete = &cqlCompleter{db}
	meta := metadata.New(db)
	return &CQL{
		db:   db,
		r:    r,
		meta: meta,
	}
}

func (c *CQL) err(err error) {
	// TODO: imrpove error display
	if _, err := fmt.Fprintf(c.r, "error: %v\n", aurora.Red(err)); err != nil {
		panic(err)
	}
}

func (c *CQL) Run() error {
	clusterInfo, err := c.meta.ClusterMeta()
	if err != nil {
		return err
	}

	if _, err := fmt.Fprintf(c.r, "Connected to %s at %v\n", aurora.Magenta(clusterInfo.Name), clusterInfo.Address); err != nil {
		return err
	}

	if _, err := fmt.Fprintf(c.r, "[gocqlsh | Cassandra %s | CQL Spec %s | Native Protocol %s]\n", clusterInfo.Version,
		clusterInfo.CQLVersion, clusterInfo.Protocol); err != nil {
		return err
	}

	for {
		line, err := c.r.Readline()
		if err != nil {
			return err
		}

		if err := c.exec(line); err != nil {
			c.err(err)
		}

	}
}

func (c *CQL) executeQuery(query string) error {
	iter := c.db.Query(query).Iter()

	table := tablewriter.NewWriter(c.r)
	table.SetAutoFormatHeaders(false)
	var header, columns []string
	for _, col := range iter.Columns() {
		header = append(header, aurora.Red(col.Name).String())
		columns = append(columns, col.Name)
	}

	table.SetHeader(header)
	table.SetAlignment(tablewriter.ALIGN_RIGHT)

	rows, err := iter.SliceMap()
	if err != nil {
		// TODO: write errors to repl
		return err
	}

	line := make([]string, len(columns))
	for _, row := range rows {
		for i, col := range columns {
			line[i] = fmt.Sprintf("%v", row[col])
		}
		table.Append(line)
	}

	table.Render()

	// TODO: store page state and query here so that we can let the user page through results with space

	return iter.Close()
}

func (c *CQL) exec(line string) error {
	// TODO: parse and do other things
	return c.executeQuery(line)
}
<commit_msg>fix typo<commit_after>package repl

import (
	"fmt"

	"github.com/gocql/gocql"
	"github.com/gocql/gocqlsh/metadata"

	"github.com/chzyer/readline"
	"github.com/logrusorgru/aurora"
	"github.com/olekukonko/tablewriter"
)

type CQL struct {
	db   *gocql.Session
	r    *readline.Instance
	meta *metadata.Cassandra
}

func New(db *gocql.Session, r *readline.Instance) *CQL {
	// TODO: protbably want to pass this in for testing
	r.Config.AutoComplete = &cqlCompleter{db}
	meta := metadata.New(db)
	return &CQL{
		db:   db,
		r:    r,
		meta: meta,
	}
}

func (c *CQL) err(err error) {
	// TODO: improve error display
	if _, err := fmt.Fprintf(c.r, "error: %v\n", aurora.Red(err)); err != nil {
		panic(err)
	}
}

func (c *CQL) Run() error {
	clusterInfo, err := c.meta.ClusterMeta()
	if err != nil {
		return err
	}

	if _, err := fmt.Fprintf(c.r, "Connected to %s at %v\n", aurora.Magenta(clusterInfo.Name), clusterInfo.Address); err != nil {
		return err
	}

	if _, err := fmt.Fprintf(c.r, "[gocqlsh | Cassandra %s | CQL Spec %s | Native Protocol %s]\n", clusterInfo.Version,
		clusterInfo.CQLVersion, clusterInfo.Protocol); err != nil {
		return err
	}

	for {
		line, err := c.r.Readline()
		if err != nil {
			return err
		}

		if err := c.exec(line); err != nil {
			c.err(err)
		}

	}
}

func (c *CQL) executeQuery(query string) error {
	iter := c.db.Query(query).Iter()

	table := tablewriter.NewWriter(c.r)
	table.SetAutoFormatHeaders(false)
	var header, columns []string
	for _, col := range iter.Columns() {
		header = append(header, aurora.Red(col.Name).String())
		columns = append(columns, col.Name)
	}

	table.SetHeader(header)
	table.SetAlignment(tablewriter.ALIGN_RIGHT)

	rows, err := iter.SliceMap()
	if err != nil {
		// TODO: write errors to repl
		return err
	}

	line := make([]string, len(columns))
	for _, row := range rows {
		for i, col := range columns {
			line[i] = fmt.Sprintf("%v", row[col])
		}
		table.Append(line)
	}

	table.Render()

	// TODO: store page state and query here so that we can let the user page through results with space

	return iter.Close()
}

func (c *CQL) exec(line string) error {
	// TODO: parse and do other things
	return c.executeQuery(line)
}
<|endoftext|>


<commit_before>package repo

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path"

	"github.com/OpenBazaar/openbazaar-go/ipfs"
	"github.com/ipfs/go-ipfs/core"
	"github.com/ipfs/go-ipfs/namesys"
	"github.com/ipfs/go-ipfs/repo/fsrepo"
	"github.com/op/go-logging"
	"github.com/tyler-smith/go-bip39"
)

var log = logging.MustGetLogger("repo")
var ErrRepoExists = errors.New("IPFS configuration file exists. Reinitializing would overwrite your keys. Use -f to force overwrite.")

func DoInit(repoRoot string, nBitsForKeypair int, testnet bool, password string, mnemonic string, dbInit func(string, []byte, string) error) error {
	if err := maybeCreateOBDirectories(repoRoot); err != nil {
		return err
	}

	if fsrepo.IsInitialized(repoRoot) {
		return ErrRepoExists
	}

	if err := checkWriteable(repoRoot); err != nil {
		return err
	}

	conf, err := InitConfig(repoRoot)
	if err != nil {
		return err
	}

	if mnemonic == "" {
		mnemonic, err = createMnemonic(bip39.NewEntropy, bip39.NewMnemonic)
		if err != nil {
			return err
		}
	}
	seed := bip39.NewSeed(mnemonic, "Secret Passphrase")
	fmt.Printf("Generating Ed25519 keypair...")
	identityKey, err := ipfs.IdentityKeyFromSeed(seed, nBitsForKeypair)
	if err != nil {
		return err
	}
	fmt.Printf("Done\n")

	identity, err := ipfs.IdentityFromKey(identityKey)
	if err != nil {
		return err
	}

	log.Infof("Initializing OpenBazaar node at %s\n", repoRoot)
	if err := fsrepo.Init(repoRoot, conf); err != nil {
		return err
	}
	conf.Identity = identity

	if err := addConfigExtensions(repoRoot, testnet); err != nil {
		return err
	}

	if err := dbInit(mnemonic, identityKey, password); err != nil {
		return err
	}

	return initializeIpnsKeyspace(repoRoot, identityKey)
}

func maybeCreateOBDirectories(repoRoot string) error {
	if err := os.MkdirAll(path.Join(repoRoot, "root"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "listings"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "ratings"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "tiny"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "small"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "medium"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "large"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "original"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "feed"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "channel"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "files"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "outbox"), os.ModePerm); err != nil {
		return err
	}
	return nil
}

func checkWriteable(dir string) error {
	_, err := os.Stat(dir)
	if err == nil {
		// Directory exists, make sure we can write to it
		testfile := path.Join(dir, "test")
		fi, err := os.Create(testfile)
		if err != nil {
			if os.IsPermission(err) {
				return fmt.Errorf("%s is not writeable by the current user", dir)
			}
			return fmt.Errorf("Unexpected error while checking writeablility of repo root: %s", err)
		}
		fi.Close()
		return os.Remove(testfile)
	}

	if os.IsNotExist(err) {
		// Directory does not exist, check that we can create it
		return os.Mkdir(dir, 0775)
	}

	if os.IsPermission(err) {
		return fmt.Errorf("Cannot write to %s, incorrect permissions", err)
	}

	return err
}

func initializeIpnsKeyspace(repoRoot string, privKeyBytes []byte) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r, err := fsrepo.Open(repoRoot)
	if err != nil { // NB: repo is owned by the node
		return err
	}
	cfg, err := r.Config()
	if err != nil {
		log.Error(err)
		return err
	}
	identity, err := ipfs.IdentityFromKey(privKeyBytes)
	if err != nil {
		return err
	}

	cfg.Identity = identity
	nd, err := core.NewNode(ctx, &core.BuildCfg{Repo: r})
	if err != nil {
		return err
	}
	defer nd.Close()

	err = nd.SetupOfflineRouting()
	if err != nil {
		return err
	}

	return namesys.InitializeKeyspace(ctx, nd.DAG, nd.Namesys, nd.Pinning, nd.PrivateKey)
}

func addConfigExtensions(repoRoot string, testnet bool) error {
	r, err := fsrepo.Open(repoRoot)
	if err != nil { // NB: repo is owned by the node
		return err
	}
	var w WalletConfig = WalletConfig{
		Type:             "spvwallet",
		MaxFee:           2000,
		FeeAPI:           "https://bitcoinfees.21.co/api/v1/fees/recommended",
		HighFeeDefault:   60,
		MediumFeeDefault: 40,
		LowFeeDefault:    20,
		TrustedPeer:      "",
	}

	var a APIConfig = APIConfig{
		Enabled:     true,
		AllowedIPs:  []string{},
		HTTPHeaders: nil,
	}

	var t TorConfig = TorConfig{}
	if err := extendConfigFile(r, "Wallet", w); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Resolver", "https://resolver.onename.com/"); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Crosspost-gateways", []string{"http://gateway.ob1.io/"}); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Dropbox-api-token", ""); err != nil {
		return err
	}
	if err := extendConfigFile(r, "JSON-API", a); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Tor-config", t); err != nil {
		return err
	}
	if err := r.Close(); err != nil {
		return err
	}
	return nil
}

func createMnemonic(newEntropy func(int) ([]byte, error), newMnemonic func([]byte) (string, error)) (string, error) {
	entropy, err := newEntropy(128)
	if err != nil {
		return "", err
	}
	mnemonic, err := newMnemonic(entropy)
	if err != nil {
		return "", err
	}
	return mnemonic, nil
}
<commit_msg>Bump default fees<commit_after>package repo

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path"

	"github.com/OpenBazaar/openbazaar-go/ipfs"
	"github.com/ipfs/go-ipfs/core"
	"github.com/ipfs/go-ipfs/namesys"
	"github.com/ipfs/go-ipfs/repo/fsrepo"
	"github.com/op/go-logging"
	"github.com/tyler-smith/go-bip39"
)

var log = logging.MustGetLogger("repo")
var ErrRepoExists = errors.New("IPFS configuration file exists. Reinitializing would overwrite your keys. Use -f to force overwrite.")

func DoInit(repoRoot string, nBitsForKeypair int, testnet bool, password string, mnemonic string, dbInit func(string, []byte, string) error) error {
	if err := maybeCreateOBDirectories(repoRoot); err != nil {
		return err
	}

	if fsrepo.IsInitialized(repoRoot) {
		return ErrRepoExists
	}

	if err := checkWriteable(repoRoot); err != nil {
		return err
	}

	conf, err := InitConfig(repoRoot)
	if err != nil {
		return err
	}

	if mnemonic == "" {
		mnemonic, err = createMnemonic(bip39.NewEntropy, bip39.NewMnemonic)
		if err != nil {
			return err
		}
	}
	seed := bip39.NewSeed(mnemonic, "Secret Passphrase")
	fmt.Printf("Generating Ed25519 keypair...")
	identityKey, err := ipfs.IdentityKeyFromSeed(seed, nBitsForKeypair)
	if err != nil {
		return err
	}
	fmt.Printf("Done\n")

	identity, err := ipfs.IdentityFromKey(identityKey)
	if err != nil {
		return err
	}

	log.Infof("Initializing OpenBazaar node at %s\n", repoRoot)
	if err := fsrepo.Init(repoRoot, conf); err != nil {
		return err
	}
	conf.Identity = identity

	if err := addConfigExtensions(repoRoot, testnet); err != nil {
		return err
	}

	if err := dbInit(mnemonic, identityKey, password); err != nil {
		return err
	}

	return initializeIpnsKeyspace(repoRoot, identityKey)
}

func maybeCreateOBDirectories(repoRoot string) error {
	if err := os.MkdirAll(path.Join(repoRoot, "root"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "listings"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "ratings"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "tiny"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "small"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "medium"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "large"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "images", "original"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "feed"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "channel"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "root", "files"), os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(repoRoot, "outbox"), os.ModePerm); err != nil {
		return err
	}
	return nil
}

func checkWriteable(dir string) error {
	_, err := os.Stat(dir)
	if err == nil {
		// Directory exists, make sure we can write to it
		testfile := path.Join(dir, "test")
		fi, err := os.Create(testfile)
		if err != nil {
			if os.IsPermission(err) {
				return fmt.Errorf("%s is not writeable by the current user", dir)
			}
			return fmt.Errorf("Unexpected error while checking writeablility of repo root: %s", err)
		}
		fi.Close()
		return os.Remove(testfile)
	}

	if os.IsNotExist(err) {
		// Directory does not exist, check that we can create it
		return os.Mkdir(dir, 0775)
	}

	if os.IsPermission(err) {
		return fmt.Errorf("Cannot write to %s, incorrect permissions", err)
	}

	return err
}

func initializeIpnsKeyspace(repoRoot string, privKeyBytes []byte) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r, err := fsrepo.Open(repoRoot)
	if err != nil { // NB: repo is owned by the node
		return err
	}
	cfg, err := r.Config()
	if err != nil {
		log.Error(err)
		return err
	}
	identity, err := ipfs.IdentityFromKey(privKeyBytes)
	if err != nil {
		return err
	}

	cfg.Identity = identity
	nd, err := core.NewNode(ctx, &core.BuildCfg{Repo: r})
	if err != nil {
		return err
	}
	defer nd.Close()

	err = nd.SetupOfflineRouting()
	if err != nil {
		return err
	}

	return namesys.InitializeKeyspace(ctx, nd.DAG, nd.Namesys, nd.Pinning, nd.PrivateKey)
}

func addConfigExtensions(repoRoot string, testnet bool) error {
	r, err := fsrepo.Open(repoRoot)
	if err != nil { // NB: repo is owned by the node
		return err
	}
	var w WalletConfig = WalletConfig{
		Type:             "spvwallet",
		MaxFee:           2000,
		FeeAPI:           "https://bitcoinfees.21.co/api/v1/fees/recommended",
		HighFeeDefault:   160,
		MediumFeeDefault: 140,
		LowFeeDefault:    120,
		TrustedPeer:      "",
	}

	var a APIConfig = APIConfig{
		Enabled:     true,
		AllowedIPs:  []string{},
		HTTPHeaders: nil,
	}

	var t TorConfig = TorConfig{}
	if err := extendConfigFile(r, "Wallet", w); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Resolver", "https://resolver.onename.com/"); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Crosspost-gateways", []string{"http://gateway.ob1.io/"}); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Dropbox-api-token", ""); err != nil {
		return err
	}
	if err := extendConfigFile(r, "JSON-API", a); err != nil {
		return err
	}
	if err := extendConfigFile(r, "Tor-config", t); err != nil {
		return err
	}
	if err := r.Close(); err != nil {
		return err
	}
	return nil
}

func createMnemonic(newEntropy func(int) ([]byte, error), newMnemonic func([]byte) (string, error)) (string, error) {
	entropy, err := newEntropy(128)
	if err != nil {
		return "", err
	}
	mnemonic, err := newMnemonic(entropy)
	if err != nil {
		return "", err
	}
	return mnemonic, nil
}
<|endoftext|>


<commit_before>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package repr contains functions useful for serializing and deserializing
// directory listing structs.
package repr

import (
	"code.google.com/p/goprotobuf/proto"
	"fmt"
	"github.com/jacobsa/comeback/fs"
)

func convertType(t fs.EntryType) DirectoryEntryProto_Type {
	switch t {
	case fs.TypeFile:
		return DirectoryEntryProto_TYPE_FILE
	case fs.TypeDirectory:
		return DirectoryEntryProto_TYPE_DIRECTORY
	case fs.TypeSymlink:
		return DirectoryEntryProto_TYPE_SYMLINK
	}

	panic(fmt.Sprintf("Unrecognized EntryType: %v", t))
}

func makeEntryProto(entry fs.DirectoryEntry) *DirectoryEntryProto {
	blobs := []*BlobInfoProto{}
	for _, score := range entry.Scores {
		proto := &BlobInfoProto{Hash: score.Sha1Hash()}
		blobs = append(blobs, proto)
	}

	return &DirectoryEntryProto{
		Type:        convertType(entry.Type).Enum(),
		Permissions: proto.Uint32(entry.Permissions),
		Name:        entry.Name,
		Mtime: &TimeProto{
			Second:     proto.Int64(entry.MTime.Unix()),
			Nanosecond: proto.Uint32(uint32(entry.MTime.Nanosecond())),
		},
		Blob: blobs,
	}
}

// Marshal turns a list of directory entries into a string that can later be
// used with Unmarshal.
func Marshal(entries []fs.DirectoryEntry) (s string, err error) {
	return "TODO", nil
}

// Unmarshal recovers a list of directory entries from a string previously
// created by Marshal.
func Unmarshal(s string) (entries []fs.DirectoryEntry, err error) {
	return nil, fmt.Errorf("TODO")
}
<commit_msg>Fixed return types.<commit_after>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package repr contains functions useful for serializing and deserializing
// directory listing structs.
package repr

import (
	"code.google.com/p/goprotobuf/proto"
	"fmt"
	"github.com/jacobsa/comeback/fs"
)

func convertType(t fs.EntryType) DirectoryEntryProto_Type {
	switch t {
	case fs.TypeFile:
		return DirectoryEntryProto_TYPE_FILE
	case fs.TypeDirectory:
		return DirectoryEntryProto_TYPE_DIRECTORY
	case fs.TypeSymlink:
		return DirectoryEntryProto_TYPE_SYMLINK
	}

	panic(fmt.Sprintf("Unrecognized EntryType: %v", t))
}

func makeEntryProto(entry fs.DirectoryEntry) *DirectoryEntryProto {
	blobs := []*BlobInfoProto{}
	for _, score := range entry.Scores {
		proto := &BlobInfoProto{Hash: score.Sha1Hash()}
		blobs = append(blobs, proto)
	}

	return &DirectoryEntryProto{
		Type:        convertType(entry.Type).Enum(),
		Permissions: proto.Uint32(entry.Permissions),
		Name:        entry.Name,
		Mtime: &TimeProto{
			Second:     proto.Int64(entry.MTime.Unix()),
			Nanosecond: proto.Uint32(uint32(entry.MTime.Nanosecond())),
		},
		Blob: blobs,
	}
}

// Marshal turns a list of directory entries into bytes that can later be used
// with Unmarshal.
func Marshal(entries []fs.DirectoryEntry) (d []byte, err error) {
	return "TODO", nil
}

// Unmarshal recovers a list of directory entries from bytes previously
// returned by Marshal.
func Unmarshal(d []byte) (entries []fs.DirectoryEntry, err error) {
	return nil, fmt.Errorf("TODO")
}
<|endoftext|>


<commit_before>package dcnet

import (
	"bytes"
	"fmt"
	"github.com/lbarman/prifi/prifi-lib/config"
	"gopkg.in/dedis/crypto.v0/abstract"
	"testing"
)

type TestGroup struct {
	Relay    *TestNode
	Clients  []*TestNode
	Trustees []*TestNode
}

type TestNode struct {
	name          string
	pubKey        abstract.Point
	privKey       abstract.Scalar
	peerKeys      []abstract.Point
	sharedSecrets []abstract.Cipher
	History       abstract.Cipher
	DCNetEntity   *DCNetEntity
}

func TestDCNetCreation(t *testing.T) {

	nRounds := int32(100)
	dcNetMessageLength := 100

	for nTrustees := 1; nTrustees < 3; nTrustees++ {
		for nClients := 1; nClients < 3; nClients++ {
			VariousLevelsOfProtection(t, nRounds, dcNetMessageLength, nClients, nTrustees)
		}
	}
}

func VariousLevelsOfProtection(t *testing.T, nRounds int32, dcNetMessageSize, NClients, NTrustees int) {
	tg := NewTestGroup(t, false, dcNetMessageSize, NClients, NTrustees)
	SimulateRounds(t, tg, nRounds)
	tg = NewTestGroup(t, true, dcNetMessageSize, NClients, NTrustees)
	SimulateRounds(t, tg, nRounds)
}

func NewTestGroup(t *testing.T, equivocationProtectionEnabled bool, dcNetMessageSize, nclients, ntrustees int) *TestGroup {

	// Use a pseudorandom stream from a well-known seed
	// for all our setup randomness,
	// so we can reproduce the same keys etc on each node.
	rand := config.CryptoSuite.Cipher([]byte("DCTest"))

	nodes := make([]*TestNode, nclients+ntrustees)
	base := config.CryptoSuite.Point().Base()
	for i := range nodes {
		nodes[i] = new(TestNode)
		nodes[i].privKey = config.CryptoSuite.Scalar().Pick(rand)
		nodes[i].pubKey = config.CryptoSuite.Point().Mul(base, nodes[i].privKey)
	}

	clients := nodes[:nclients]
	trustees := nodes[nclients:]

	relay := new(TestNode)
	relay.name = "Relay"
	relay.DCNetEntity = NewDCNetEntity(0, DCNET_RELAY, dcNetMessageSize, equivocationProtectionEnabled, nil)

	// Create tables of the clients' and the trustees' public session keys
	clientsKeys := make([]abstract.Point, nclients)
	trusteesKeys := make([]abstract.Point, ntrustees)
	for i := range clients {
		clientsKeys[i] = clients[i].pubKey
	}
	for i := range trustees {
		trusteesKeys[i] = trustees[i].pubKey
	}

	// Setup the clients and servers to know each others' session keys.
	for i, n := range clients {
		// Form Diffie-Hellman secret shared with each peer,
		// and a pseudorandom cipher derived from each.
		n.name = fmt.Sprintf("Client-%d", i)
		n.peerKeys = trusteesKeys
		n.sharedSecrets = make([]abstract.Cipher, len(n.peerKeys))
		for i := range n.peerKeys {
			dh := config.CryptoSuite.Point().Mul(n.peerKeys[i], n.privKey)
			data, _ := dh.MarshalBinary()
			n.sharedSecrets[i] = config.CryptoSuite.Cipher(data)
		}
		n.DCNetEntity = NewDCNetEntity(i, DCNET_CLIENT, dcNetMessageSize, equivocationProtectionEnabled, n.sharedSecrets)
	}

	for i, n := range trustees {
		// Form Diffie-Hellman secret shared with each peer,
		// and a pseudorandom cipher derived from each.
		n.name = fmt.Sprintf("Trustee-%d", i)
		n.peerKeys = clientsKeys
		n.sharedSecrets = make([]abstract.Cipher, len(n.peerKeys))
		for i := range n.peerKeys {
			dh := config.CryptoSuite.Point().Mul(n.peerKeys[i], n.privKey)
			data, _ := dh.MarshalBinary()
			n.sharedSecrets[i] = config.CryptoSuite.Cipher(data)
		}
		n.DCNetEntity = NewDCNetEntity(i, DCNET_TRUSTEE, dcNetMessageSize, equivocationProtectionEnabled, n.sharedSecrets)
	}

	// Create a set of fake history streams for the relay and clients
	//hist := []byte("xyz")
	//relay.History = suite.Cipher(hist)
	//for i := range clients {
	//	clients[i].History = suite.Cipher(hist)
	//}

	tg := new(TestGroup)
	tg.Relay = relay
	tg.Clients = clients
	tg.Trustees = trustees
	return tg
}

func SimulateRounds(t *testing.T, tg *TestGroup, maxRounds int32) {

	d := tg.Relay.DCNetEntity
	fmt.Println("Testing for ", len(tg.Clients), "/", len(tg.Trustees),
		"DC-net with equiv=", d.EquivocationProtectionEnabled)

	for roundID := int32(0); roundID <= maxRounds; roundID += 2 {
		clientMessages := make([][]byte, 0)
		trusteesMessages := make([][]byte, 0)
		first := true
		message := randomBytes(d.GetPayloadSize())

		downstreamMessage := randomBytes(d.GetPayloadSize()) //used only to update the history
		for i := range tg.Clients {
			tg.Clients[i].DCNetEntity.UpdateReceivedMessageHistory(downstreamMessage)
		}
		tg.Relay.DCNetEntity.UpdateReceivedMessageHistory(downstreamMessage)

		// Generate the clients dc-net cryptographic material
		for i := range tg.Clients {
			var m []byte
			if first {
				//fmt.Println("Embedding message:", message)
				m = tg.Clients[i].DCNetEntity.EncodeForRound(roundID, true, message)
				first = false
			} else {
				m = tg.Clients[i].DCNetEntity.EncodeForRound(roundID, false, nil)
			}
			clientMessages = append(clientMessages, m)
		}

		// Generate the trustees dc-net cryptographic material
		for i := range tg.Trustees {
			m := tg.Trustees[i].DCNetEntity.TrusteeEncodeForRound(roundID)
			trusteesMessages = append(trusteesMessages, m)
		}

		// The relay decodes the cryptographic material
		tg.Relay.DCNetEntity.DecodeStart(roundID)
		for _, m := range clientMessages {
			tg.Relay.DCNetEntity.DecodeClient(roundID, m)
		}
		for _, m := range trusteesMessages {
			tg.Relay.DCNetEntity.DecodeTrustee(roundID, m)
		}

		output := tg.Relay.DCNetEntity.DecodeCell()

		//fmt.Println("-----------------")
		//fmt.Println(output)
		//fmt.Println(message)

		if !bytes.Equal(output, message) {
			t.Error("DC-net encoding failed")
		}
	}
}
<commit_msg>Increase range of dcnet_test.go<commit_after>package dcnet

import (
	"bytes"
	"fmt"
	"github.com/lbarman/prifi/prifi-lib/config"
	"gopkg.in/dedis/crypto.v0/abstract"
	"testing"
)

type TestGroup struct {
	Relay    *TestNode
	Clients  []*TestNode
	Trustees []*TestNode
}

type TestNode struct {
	name          string
	pubKey        abstract.Point
	privKey       abstract.Scalar
	peerKeys      []abstract.Point
	sharedSecrets []abstract.Cipher
	History       abstract.Cipher
	DCNetEntity   *DCNetEntity
}

func TestDCNetCreation(t *testing.T) {

	nRounds := int32(100)
	dcNetMessageLength := 100

	for nTrustees := 1; nTrustees < 10; nTrustees++ {
		for nClients := 1; nClients < 10; nClients++ {
			VariousLevelsOfProtection(t, nRounds, dcNetMessageLength, nClients, nTrustees)
		}
	}
}

func VariousLevelsOfProtection(t *testing.T, nRounds int32, dcNetMessageSize, NClients, NTrustees int) {
	tg := NewTestGroup(t, false, dcNetMessageSize, NClients, NTrustees)
	SimulateRounds(t, tg, nRounds)
	tg = NewTestGroup(t, true, dcNetMessageSize, NClients, NTrustees)
	SimulateRounds(t, tg, nRounds)
}

func NewTestGroup(t *testing.T, equivocationProtectionEnabled bool, dcNetMessageSize, nclients, ntrustees int) *TestGroup {

	// Use a pseudorandom stream from a well-known seed
	// for all our setup randomness,
	// so we can reproduce the same keys etc on each node.
	rand := config.CryptoSuite.Cipher([]byte("DCTest"))

	nodes := make([]*TestNode, nclients+ntrustees)
	base := config.CryptoSuite.Point().Base()
	for i := range nodes {
		nodes[i] = new(TestNode)
		nodes[i].privKey = config.CryptoSuite.Scalar().Pick(rand)
		nodes[i].pubKey = config.CryptoSuite.Point().Mul(base, nodes[i].privKey)
	}

	clients := nodes[:nclients]
	trustees := nodes[nclients:]

	relay := new(TestNode)
	relay.name = "Relay"
	relay.DCNetEntity = NewDCNetEntity(0, DCNET_RELAY, dcNetMessageSize, equivocationProtectionEnabled, nil)

	// Create tables of the clients' and the trustees' public session keys
	clientsKeys := make([]abstract.Point, nclients)
	trusteesKeys := make([]abstract.Point, ntrustees)
	for i := range clients {
		clientsKeys[i] = clients[i].pubKey
	}
	for i := range trustees {
		trusteesKeys[i] = trustees[i].pubKey
	}

	// Setup the clients and servers to know each others' session keys.
	for i, n := range clients {
		// Form Diffie-Hellman secret shared with each peer,
		// and a pseudorandom cipher derived from each.
		n.name = fmt.Sprintf("Client-%d", i)
		n.peerKeys = trusteesKeys
		n.sharedSecrets = make([]abstract.Cipher, len(n.peerKeys))
		for i := range n.peerKeys {
			dh := config.CryptoSuite.Point().Mul(n.peerKeys[i], n.privKey)
			data, _ := dh.MarshalBinary()
			n.sharedSecrets[i] = config.CryptoSuite.Cipher(data)
		}
		n.DCNetEntity = NewDCNetEntity(i, DCNET_CLIENT, dcNetMessageSize, equivocationProtectionEnabled, n.sharedSecrets)
	}

	for i, n := range trustees {
		// Form Diffie-Hellman secret shared with each peer,
		// and a pseudorandom cipher derived from each.
		n.name = fmt.Sprintf("Trustee-%d", i)
		n.peerKeys = clientsKeys
		n.sharedSecrets = make([]abstract.Cipher, len(n.peerKeys))
		for i := range n.peerKeys {
			dh := config.CryptoSuite.Point().Mul(n.peerKeys[i], n.privKey)
			data, _ := dh.MarshalBinary()
			n.sharedSecrets[i] = config.CryptoSuite.Cipher(data)
		}
		n.DCNetEntity = NewDCNetEntity(i, DCNET_TRUSTEE, dcNetMessageSize, equivocationProtectionEnabled, n.sharedSecrets)
	}

	// Create a set of fake history streams for the relay and clients
	//hist := []byte("xyz")
	//relay.History = suite.Cipher(hist)
	//for i := range clients {
	//	clients[i].History = suite.Cipher(hist)
	//}

	tg := new(TestGroup)
	tg.Relay = relay
	tg.Clients = clients
	tg.Trustees = trustees
	return tg
}

func SimulateRounds(t *testing.T, tg *TestGroup, maxRounds int32) {

	d := tg.Relay.DCNetEntity
	fmt.Println("Testing for ", len(tg.Clients), "/", len(tg.Trustees),
		"DC-net with equiv=", d.EquivocationProtectionEnabled)

	for roundID := int32(0); roundID <= maxRounds; roundID += 2 {
		clientMessages := make([][]byte, 0)
		trusteesMessages := make([][]byte, 0)
		first := true
		message := randomBytes(d.GetPayloadSize())

		downstreamMessage := randomBytes(d.GetPayloadSize()) //used only to update the history
		for i := range tg.Clients {
			tg.Clients[i].DCNetEntity.UpdateReceivedMessageHistory(downstreamMessage)
		}
		tg.Relay.DCNetEntity.UpdateReceivedMessageHistory(downstreamMessage)

		// Generate the clients dc-net cryptographic material
		for i := range tg.Clients {
			var m []byte
			if first {
				//fmt.Println("Embedding message:", message)
				m = tg.Clients[i].DCNetEntity.EncodeForRound(roundID, true, message)
				first = false
			} else {
				m = tg.Clients[i].DCNetEntity.EncodeForRound(roundID, false, nil)
			}
			clientMessages = append(clientMessages, m)
		}

		// Generate the trustees dc-net cryptographic material
		for i := range tg.Trustees {
			m := tg.Trustees[i].DCNetEntity.TrusteeEncodeForRound(roundID)
			trusteesMessages = append(trusteesMessages, m)
		}

		// The relay decodes the cryptographic material
		tg.Relay.DCNetEntity.DecodeStart(roundID)
		for _, m := range clientMessages {
			tg.Relay.DCNetEntity.DecodeClient(roundID, m)
		}
		for _, m := range trusteesMessages {
			tg.Relay.DCNetEntity.DecodeTrustee(roundID, m)
		}

		output := tg.Relay.DCNetEntity.DecodeCell()

		//fmt.Println("-----------------")
		//fmt.Println(output)
		//fmt.Println(message)

		if !bytes.Equal(output, message) {
			t.Error("DC-net encoding failed")
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>Removing dummy metrics<commit_after><|endoftext|>


<commit_before>// From Fyne GUI book by Andrew Williams, Chapter 6, widget.go

package main

import (
	"encoding/gob"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"log"
	"os"

	//"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"image/color"
	"runtime"
	"strconv"
	"strings"

	"src/hpcalc2"
)

const lastModified = "Sep 5, 2021"

var globalA fyne.App
var globalW fyne.Window

var green = color.NRGBA{R: 0, G: 100, B: 0, A: 255}
var red = color.NRGBA{R: 100, G: 0, B: 0, A: 255}
var blue = color.NRGBA{R: 0, G: 0, B: 100, A: 255}
var gray = color.Gray{Y: 100}
var cyan = color.NRGBA{R: 0, G: 255, B: 255, A: 255}
var lightcyan = color.NRGBA{R: 224, G: 255, B: 255, A: 255}

var homeDir string
var windowsFlag bool
var Storage [36]float64 // 0 ..  9, a ..  z
var DisplayTape, stringslice []string

const Storage1FileName = "RPNStorage.gob" // Allows for a rotation of Storage files, in case of a mistake.
const Storage2FileName = "RPNStorage2.gob"
const Storage3FileName = "RPNStorage3.gob"
const DisplayTapeFilename = "displaytape.txt"

func main() {
	fmt.Printf(" rpnf.go, using fyne.io v2.  Last modified %s, compiled using %s.\n", lastModified, runtime.Version())

	var Stk hpcalc2.StackType // used when time to write out the stack upon exit.
	var err error
	DisplayTape = make([]string, 0, 100)
	theFileExists := true

	homeDir, err = os.UserHomeDir() // this function became available as of Go 1.12
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error from os.UserHomeDir() is", err)
		os.Exit(1)
	}
	windowsFlag = runtime.GOOS == "windows"

	StorageFullFilenameSlice := make([]string, 5)
	StorageFullFilenameSlice[0] = homeDir
	StorageFullFilenameSlice[1] = string(os.PathSeparator)
	StorageFullFilenameSlice[2] = Storage1FileName
	StorageFullFilename := strings.Join(StorageFullFilenameSlice, "")
/*
	Storage2FullFilenameSlice := make([]string, 5)
	Storage2FullFilenameSlice[0] = homeDir
	Storage2FullFilenameSlice[1] = string(os.PathSeparator)
	Storage2FullFilenameSlice[2] = Storage2FileName
	Storage2FullFilename := strings.Join(Storage2FullFilenameSlice, "")

	Storage3FullFilenameSlice := make([]string, 5)
	Storage3FullFilenameSlice[0] = homeDir
	Storage3FullFilenameSlice[1] = string(os.PathSeparator)
	Storage3FullFilenameSlice[2] = Storage3FileName
	Storage3FullFilename := strings.Join(Storage3FullFilenameSlice, "")

 */

	var thefile *os.File

	thefile, err = os.Open(StorageFullFilename) // open for reading
	if err != nil {
		fmt.Printf(" Error from os.Open(Storage1FileName).  Possibly because no Stack File found: %v\n", err)
		theFileExists = false
	}
	defer thefile.Close()
	if theFileExists {
		decoder := gob.NewDecoder(thefile)       // decoder reads the file.
		err = decoder.Decode(&Stk)               // decoder reads the file.
		check(err)                               // theFileExists, so panic if this is an error.
		for i := hpcalc2.T1; i >= hpcalc2.X; i-- { // Push in reverse onto the stack in hpcalc2.
			hpcalc2.PUSHX(Stk[i])
		}

		err = decoder.Decode(&Storage) // decoder reads the file.
		check(err)                     // theFileExists, so panic if this is an error.

		thefile.Close()
	}

	globalA = app.New()
	globalW = globalA.NewWindow("Widget Binding")
	globalW.Canvas().SetOnTypedKey(keyTyped)
	R, _ := hpcalc2.GetResult("t")
	_, ss := hpcalc2.GetResult("dump")
	ssJoined := strings.Join(ss, "\n")
	//shorterSS := ss[1 : len(ss)-1] // removes the first and last strings, which are only character delims
	//shorterSSjoined := strings.Join(shorterSS, "\n")

	resultStr := strconv.FormatFloat(R, 'g', -1, 64)
	resultStr = hpcalc2.CropNStr(resultStr)
	resultLabel := canvas.NewText("X = "+resultStr, cyan)
	resultLabel.TextSize = 42
	resultLabel.Alignment = fyne.TextAlignCenter

    stackLabel := widget.NewLabel(ssJoined)

	input := widget.NewEntry()
	input.PlaceHolder = "Enter expression or command"
	enterfunc := func(s string) {
		log.Println(" func assigned closure ENTER was hit:", s)
		input.SetText("")
	}
	input.OnSubmitted = enterfunc

	content := container.NewVBox(input, resultLabel,stackLabel)

	globalW.SetContent(content)
	globalW.Resize(fyne.Size{400, 500})

	globalW.ShowAndRun()
}
func keyTyped(e *fyne.KeyEvent) { // index is a global var
	switch e.Name {
	case fyne.KeyUp:
	case fyne.KeyDown:
	case fyne.KeyLeft:
	case fyne.KeyRight:
	case fyne.KeyEscape, fyne.KeyQ, fyne.KeyX:
		globalW.Close() // quit's the app if this is the last window, which it is.
		//		(*globalA).Quit()
	case fyne.KeyHome:
	case fyne.KeyEnd:
	case fyne.KeyPageUp:
	case fyne.KeyPageDown:
	case fyne.KeyPlus:
	case fyne.KeyMinus:
	case fyne.KeyEqual:
	case fyne.KeyEnter, fyne.KeyReturn, fyne.KeySpace:
		globalA.Quit()
	case fyne.KeyBackspace:
	}
}

// ------------------------------------------------------- check -------------------------------
func check(err error) {
	if err != nil {
			panic(err)
		}
}

<commit_msg>09/06/2021 08:38:41 PM modified:   rpnf/rpnf.go<commit_after>// From Fyne GUI book by Andrew Williams, Chapter 6, widget.go

package main

import (
	"encoding/gob"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"image/color"
	"log"
	"os"
	"runtime"
	"src/hpcalc2"
	"src/tknptr"
	"strconv"
	"strings"
	"time"

	//"fyne.io/fyne/v2/data/binding"
)

const lastModified = "Sep 5, 2021"

var globalA fyne.App
var globalW fyne.Window

var green = color.NRGBA{R: 0, G: 100, B: 0, A: 255}
var red = color.NRGBA{R: 100, G: 0, B: 0, A: 255}
var blue = color.NRGBA{R: 0, G: 0, B: 100, A: 255}
var gray = color.Gray{Y: 100}
var cyan = color.NRGBA{R: 0, G: 255, B: 255, A: 255}
var lightcyan = color.NRGBA{R: 224, G: 255, B: 255, A: 255}

var homeDir string
var windowsFlag bool
var Storage [36]float64 // 0 ..  9, a ..  z
var DisplayTape, stringslice []string

const Storage1FileName = "RPNStorage.gob" // Allows for a rotation of Storage files, in case of a mistake.
const Storage2FileName = "RPNStorage2.gob"
const Storage3FileName = "RPNStorage3.gob"
const DisplayTapeFilename = "displaytape.txt"

func main() {
	fmt.Printf(" rpnf.go, using fyne.io v2.  Last modified %s, compiled using %s.\n", lastModified, runtime.Version())

	var Stk hpcalc2.StackType // used when time to write out the stack upon exit.
	var err error
	DisplayTape = make([]string, 0, 100)
	DisplayTape = append(DisplayTape, "History of entered commands")
	theFileExists := true

	homeDir, err = os.UserHomeDir() // this function became available as of Go 1.12
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error from os.UserHomeDir() is", err)
		os.Exit(1)
	}
	windowsFlag = runtime.GOOS == "windows"

	StorageFullFilenameSlice := make([]string, 5)
	StorageFullFilenameSlice[0] = homeDir
	StorageFullFilenameSlice[1] = string(os.PathSeparator)
	StorageFullFilenameSlice[2] = Storage1FileName
	StorageFullFilename := strings.Join(StorageFullFilenameSlice, "")
	/*
		Storage2FullFilenameSlice := homeDir + string(os.PathSeparator) + Storage2FileName
		Storage3FullFilenameSlice := homeDir + string(os.PathSeparator) + Storage3FileName
	*/

	var thefile *os.File

	thefile, err = os.Open(StorageFullFilename) // open for reading
	if err != nil {
		fmt.Printf(" Error from os.Open(Storage1FileName).  Possibly because no Stack File found: %v\n", err)
		theFileExists = false
	}
	defer thefile.Close()
	if theFileExists {
		decoder := gob.NewDecoder(thefile)         // decoder reads the file.
		err = decoder.Decode(&Stk)                 // decoder reads the file.
		check(err)                                 // theFileExists, so panic if this is an error.
		for i := hpcalc2.T1; i >= hpcalc2.X; i-- { // Push in reverse onto the stack in hpcalc2.
			hpcalc2.PUSHX(Stk[i])
		}

		err = decoder.Decode(&Storage) // decoder reads the file.
		check(err)                     // theFileExists, so panic if this is an error.

		thefile.Close()
	}

	globalA = app.New()
	globalW = globalA.NewWindow("Widget Binding")
	globalW.Canvas().SetOnTypedKey(keyTyped)
	R, _ := hpcalc2.GetResult("t")
	_, ss := hpcalc2.GetResult("dump")
	ssJoined := strings.Join(ss, "\n")
	//shorterSS := ss[1 : len(ss)-1] // removes the first and last strings, which are only character delims
	//shorterSSjoined := strings.Join(shorterSS, "\n")

	resultStr := strconv.FormatFloat(R, 'g', -1, 64)
	resultStr = hpcalc2.CropNStr(resultStr)
	resultLabel := canvas.NewText("X = "+resultStr, cyan)
	resultLabel.TextSize = 42
	resultLabel.Alignment = fyne.TextAlignCenter

	stackLabel := widget.NewLabel(ssJoined)

	input := widget.NewEntry()
	input.PlaceHolder = "Enter expression or command"
	enterfunc := func(s string) {
		log.Println(" func assigned closure ENTER was hit:", s)
		input.SetText("")
	}
	input.OnSubmitted = enterfunc

	regStr := OutputRegToString()
	regLabel := widget.NewLabel(regStr)

	leftColumn := container.NewVBox(input, resultLabel, stackLabel, regLabel)

	displayString := strings.Join(DisplayTape, "\n")
	displayLabel := widget.NewLabel(displayString)
	paddingLabel := widget.NewLabel("\n \n \n \n")

	go showHelp()

	rightColumn := container.NewVBox(paddingLabel, displayLabel)

	combinedColumns := container.NewHBox(leftColumn, rightColumn)

	globalW.SetContent(combinedColumns)
	globalW.Resize(fyne.Size{Width: 500, Height: 500})

	globalW.CenterOnScreen()
	globalW.ShowAndRun()
}

func keyTyped(e *fyne.KeyEvent) { // index is a global var
	switch e.Name {
	case fyne.KeyUp:
	case fyne.KeyDown:
	case fyne.KeyLeft:
	case fyne.KeyRight:
	case fyne.KeyEscape, fyne.KeyQ, fyne.KeyX:
		globalW.Close() // quit's the app if this is the last window, which it is.
		//		(*globalA).Quit()
	case fyne.KeyHome:
	case fyne.KeyEnd:
	case fyne.KeyPageUp:
	case fyne.KeyPageDown:
	case fyne.KeyPlus:
	case fyne.KeyMinus:
	case fyne.KeyEqual:
	case fyne.KeyEnter, fyne.KeyReturn, fyne.KeySpace:
		globalA.Quit()
	case fyne.KeyBackspace:
	}
}

// ------------------------------------------------------- check -------------------------------
func check(err error) {
	if err != nil {
		panic(err)
	}
}

/* ------------------------------------------------------------ GetRegIdx --------- */

func GetRegIdx(chr byte) int {
	// Return 0..35 with A = 10 and Z = 35
	ch := tknptr.CAP(chr)
	if (ch >= '0') && (ch <= '9') {
		ch = ch - '0'
	} else if (ch >= 'A') && (ch <= 'Z') {
		ch = ch - 'A' + 10
	} else { // added 12/11/2016 to fix bug
		ch = 0
	}
	return int(ch)
} // end GetRegIdx

/*-------------------------------------------------------------- GetRegChar ------  */

func GetRegChar(idx int) string {
	/* Return '0'..'Z' with A = 10 and Z = 35 */
	const RegNames = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	if (idx < 0) || (idx > 35) {
		return "0"
	}
	ch := RegNames[idx]
	return string(ch)
} // GetRegChar

// ------------------------------------------------------------ OutputRegToString --------------

func OutputRegToString() string {
	FirstNonZeroStorageFlag := true
	ss := make([]string, 0, 40)

	for i, r := range Storage {
		if r != 0.0 {
			if FirstNonZeroStorageFlag {
				s := fmt.Sprintf("                The following storage registers are not zero")
				ss = append(ss, s)
				FirstNonZeroStorageFlag = false
			}
			ch := GetRegChar(i)
			sigfig := hpcalc2.SigFig()
			s := strconv.FormatFloat(r, 'g', sigfig, 64)
			s = hpcalc2.CropNStr(s)
			if r >= 10000 {
				s = hpcalc2.AddCommas(s)
			}
			str := fmt.Sprintf("Reg [%s] = %s", ch, s)
			ss = append(ss, str)
		} // if storage value is not zero
	} // for range over Storage
	if FirstNonZeroStorageFlag {
		s := fmt.Sprintf("All storage registers are zero.")
		ss = append(ss, s)
	}
	jointedStr := strings.Join(ss, "\n")
	return jointedStr
} // end OutputRegToString

// --------------------------------------------------------- getHelpStr ------------------------------------------

func showHelp() {

	time.Sleep(5 * time.Second)
	_, ss := hpcalc2.GetResult("help")
	helpStr := strings.Join(ss, "\n")
	helpLabel := widget.NewLabel(helpStr)
	dialog.ShowCustom("Help","OK", helpLabel, globalW)

	return
}<|endoftext|>