Search in sources :

Example 16 with Expr

use of com.microsoft.z3.Expr in project bmoth by hhu-stups.

the class SetFormulaEvaluationTest method testSetExtensionFormulaWithSingleVarModel.

@Test
public void testSetExtensionFormulaWithSingleVarModel() {
    String formula = "{1,2} = {2,x}";
    // getting the translated z3 representation of the formula
    BoolExpr constraint = translatePredicate(formula, z3Context);
    z3Solver.add(constraint);
    Status check = z3Solver.check();
    Expr x = z3Context.mkIntConst("x");
    assertEquals(Status.SATISFIABLE, check);
    assertEquals(z3Context.mkInt(1), z3Solver.getModel().eval(x, true));
}
Also used : Status(com.microsoft.z3.Status) BoolExpr(com.microsoft.z3.BoolExpr) BoolExpr(com.microsoft.z3.BoolExpr) Expr(com.microsoft.z3.Expr) Test(org.junit.Test)

Example 17 with Expr

use of com.microsoft.z3.Expr in project bmoth by hhu-stups.

the class SetFormulaEvaluationTest method testSetExtensionFormulaWithSetVarModel.

@Test
public void testSetExtensionFormulaWithSetVarModel() {
    String formula = "{1,2} = x";
    // getting the translated z3 representation of the formula
    BoolExpr constraint = translatePredicate(formula, z3Context);
    z3Solver.add(constraint);
    Status check = z3Solver.check();
    Expr x = z3Context.mkArrayConst("x", z3Context.mkIntSort(), z3Context.mkBoolSort());
    assertEquals(Status.SATISFIABLE, check);
    assertEquals("(store (store ((as const (Array Int Bool)) false) 1 true) 2 true)", z3Solver.getModel().eval(x, true).toString());
}
Also used : Status(com.microsoft.z3.Status) BoolExpr(com.microsoft.z3.BoolExpr) BoolExpr(com.microsoft.z3.BoolExpr) Expr(com.microsoft.z3.Expr) Test(org.junit.Test)

Example 18 with Expr

use of com.microsoft.z3.Expr in project batfish by batfish.

the class Encoder method buildCounterExample.

/*
   * Add the relevant variables in the counterexample to
   * display to the user in a human-readable fashion
   */
private void buildCounterExample(Encoder enc, Model m, SortedMap<String, String> model, SortedMap<String, String> packetModel, SortedSet<String> fwdModel, SortedMap<String, SortedMap<String, String>> envModel, SortedSet<String> failures) {
    SortedMap<Expr, String> valuation = new TreeMap<>();
    // If user asks for the full model
    for (Entry<String, Expr> entry : _allVariables.entrySet()) {
        String name = entry.getKey();
        Expr e = entry.getValue();
        Expr val = m.evaluate(e, true);
        if (!val.equals(e)) {
            String s = val.toString();
            if (_question.getFullModel()) {
                model.put(name, s);
            }
            valuation.put(e, s);
        }
    }
    // Packet model
    SymbolicPacket p = enc.getMainSlice().getSymbolicPacket();
    String dstIp = valuation.get(p.getDstIp());
    String srcIp = valuation.get(p.getSrcIp());
    String dstPt = valuation.get(p.getDstPort());
    String srcPt = valuation.get(p.getSrcPort());
    String icmpCode = valuation.get(p.getIcmpCode());
    String icmpType = valuation.get(p.getIcmpType());
    String ipProtocol = valuation.get(p.getIpProtocol());
    String tcpAck = valuation.get(p.getTcpAck());
    String tcpCwr = valuation.get(p.getTcpCwr());
    String tcpEce = valuation.get(p.getTcpEce());
    String tcpFin = valuation.get(p.getTcpFin());
    String tcpPsh = valuation.get(p.getTcpPsh());
    String tcpRst = valuation.get(p.getTcpRst());
    String tcpSyn = valuation.get(p.getTcpSyn());
    String tcpUrg = valuation.get(p.getTcpUrg());
    Ip dip = new Ip(Long.parseLong(dstIp));
    Ip sip = new Ip(Long.parseLong(srcIp));
    packetModel.put("dstIp", dip.toString());
    if (sip.asLong() != 0) {
        packetModel.put("srcIp", sip.toString());
    }
    if (dstPt != null && !dstPt.equals("0")) {
        packetModel.put("dstPort", dstPt);
    }
    if (srcPt != null && !srcPt.equals("0")) {
        packetModel.put("srcPort", srcPt);
    }
    if (icmpCode != null && !icmpCode.equals("0")) {
        packetModel.put("icmpCode", icmpCode);
    }
    if (icmpType != null && !icmpType.equals("0")) {
        packetModel.put("icmpType", icmpType);
    }
    if (ipProtocol != null && !ipProtocol.equals("0")) {
        Integer number = Integer.parseInt(ipProtocol);
        IpProtocol proto = IpProtocol.fromNumber(number);
        packetModel.put("protocol", proto.toString());
    }
    if ("true".equals(tcpAck)) {
        packetModel.put("tcpAck", "set");
    }
    if ("true".equals(tcpCwr)) {
        packetModel.put("tcpCwr", "set");
    }
    if ("true".equals(tcpEce)) {
        packetModel.put("tcpEce", "set");
    }
    if ("true".equals(tcpFin)) {
        packetModel.put("tcpFin", "set");
    }
    if ("true".equals(tcpPsh)) {
        packetModel.put("tcpPsh", "set");
    }
    if ("true".equals(tcpRst)) {
        packetModel.put("tcpRst", "set");
    }
    if ("true".equals(tcpSyn)) {
        packetModel.put("tcpSyn", "set");
    }
    if ("true".equals(tcpUrg)) {
        packetModel.put("tcpUrg", "set");
    }
    for (EncoderSlice slice : enc.getSlices().values()) {
        for (Entry<LogicalEdge, SymbolicRoute> entry2 : slice.getLogicalGraph().getEnvironmentVars().entrySet()) {
            LogicalEdge lge = entry2.getKey();
            SymbolicRoute r = entry2.getValue();
            if ("true".equals(valuation.get(r.getPermitted()))) {
                SortedMap<String, String> recordMap = new TreeMap<>();
                GraphEdge ge = lge.getEdge();
                String nodeIface = ge.getRouter() + "," + ge.getStart().getName() + " (BGP)";
                envModel.put(nodeIface, recordMap);
                if (r.getPrefixLength() != null) {
                    String x = valuation.get(r.getPrefixLength());
                    if (x != null) {
                        int len = Integer.parseInt(x);
                        Prefix p1 = new Prefix(dip, len);
                        recordMap.put("prefix", p1.toString());
                    }
                }
                if (r.getAdminDist() != null) {
                    String x = valuation.get(r.getAdminDist());
                    if (x != null) {
                        recordMap.put("admin distance", x);
                    }
                }
                if (r.getLocalPref() != null) {
                    String x = valuation.get(r.getLocalPref());
                    if (x != null) {
                        recordMap.put("local preference", x);
                    }
                }
                if (r.getMetric() != null) {
                    String x = valuation.get(r.getMetric());
                    if (x != null) {
                        recordMap.put("protocol metric", x);
                    }
                }
                if (r.getMed() != null) {
                    String x = valuation.get(r.getMed());
                    if (x != null) {
                        recordMap.put("multi-exit disc.", valuation.get(r.getMed()));
                    }
                }
                if (r.getOspfArea() != null && r.getOspfArea().getBitVec() != null) {
                    String x = valuation.get(r.getOspfArea().getBitVec());
                    if (x != null) {
                        Integer i = Integer.parseInt(x);
                        Long area = r.getOspfArea().value(i);
                        recordMap.put("OSPF Area", area.toString());
                    }
                }
                if (r.getOspfType() != null && r.getOspfType().getBitVec() != null) {
                    String x = valuation.get(r.getOspfType().getBitVec());
                    if (x != null) {
                        Integer i = Integer.parseInt(x);
                        OspfType type = r.getOspfType().value(i);
                        recordMap.put("OSPF Type", type.toString());
                    }
                }
                for (Entry<CommunityVar, BoolExpr> entry3 : r.getCommunities().entrySet()) {
                    CommunityVar cvar = entry3.getKey();
                    BoolExpr e = entry3.getValue();
                    String c = valuation.get(e);
                    // TODO: what about OTHER type?
                    if ("true".equals(c) && displayCommunity(cvar)) {
                        String s = cvar.getValue();
                        String t = slice.getNamedCommunities().get(cvar.getValue());
                        s = (t == null ? s : t);
                        recordMap.put("community " + s, "");
                    }
                }
            }
        }
    }
    // Forwarding Model
    enc.getMainSlice().getSymbolicDecisions().getDataForwarding().forEach((router, edge, e) -> {
        String s = valuation.get(e);
        if ("true".equals(s)) {
            SymbolicRoute r = enc.getMainSlice().getSymbolicDecisions().getBestNeighbor().get(router);
            if (r.getProtocolHistory() != null) {
                Protocol proto;
                List<Protocol> allProtocols = enc.getMainSlice().getProtocols().get(router);
                if (allProtocols.size() == 1) {
                    proto = allProtocols.get(0);
                } else {
                    s = valuation.get(r.getProtocolHistory().getBitVec());
                    int i = Integer.parseInt(s);
                    proto = r.getProtocolHistory().value(i);
                }
                fwdModel.add(edge + " (" + proto.name() + ")");
            } else {
                fwdModel.add(edge.toString());
            }
        }
    });
    _symbolicFailures.getFailedInternalLinks().forEach((x, y, e) -> {
        String s = valuation.get(e);
        if ("1".equals(s)) {
            String pair = (x.compareTo(y) < 0 ? x + "," + y : y + "," + x);
            failures.add("link(" + pair + ")");
        }
    });
    _symbolicFailures.getFailedEdgeLinks().forEach((ge, e) -> {
        String s = valuation.get(e);
        if ("1".equals(s)) {
            failures.add("link(" + ge.getRouter() + "," + ge.getStart().getName() + ")");
        }
    });
}
Also used : BoolExpr(com.microsoft.z3.BoolExpr) Ip(org.batfish.datamodel.Ip) Prefix(org.batfish.datamodel.Prefix) TreeMap(java.util.TreeMap) CommunityVar(org.batfish.symbolic.CommunityVar) BoolExpr(com.microsoft.z3.BoolExpr) ArithExpr(com.microsoft.z3.ArithExpr) BitVecExpr(com.microsoft.z3.BitVecExpr) Expr(com.microsoft.z3.Expr) IpProtocol(org.batfish.datamodel.IpProtocol) OspfType(org.batfish.symbolic.OspfType) IpProtocol(org.batfish.datamodel.IpProtocol) Protocol(org.batfish.symbolic.Protocol) GraphEdge(org.batfish.symbolic.GraphEdge)

Example 19 with Expr

use of com.microsoft.z3.Expr in project batfish by batfish.

the class EncoderSlice method addControlForwardingConstraints.

/*
   * Constraints that define control-plane forwarding.
   * If there is some valid import, then control plane forwarding
   * will occur out an interface when this is the best choice.
   * Otherwise, it will not occur.
   */
private void addControlForwardingConstraints() {
    for (Entry<String, Configuration> entry : getGraph().getConfigurations().entrySet()) {
        String router = entry.getKey();
        Configuration conf = entry.getValue();
        boolean someEdge = false;
        SymbolicRoute best = _symbolicDecisions.getBestNeighbor().get(router);
        Map<GraphEdge, BoolExpr> cfExprs = new HashMap<>();
        Set<GraphEdge> constrained = new HashSet<>();
        for (Protocol proto : getProtocols().get(router)) {
            for (LogicalEdge e : collectAllImportLogicalEdges(router, conf, proto)) {
                someEdge = true;
                constrained.add(e.getEdge());
                SymbolicRoute vars = correctVars(e);
                BoolExpr choice = _symbolicDecisions.getChoiceVariables().get(router, proto, e);
                BoolExpr isBest = mkAnd(choice, equal(conf, proto, best, vars, e, false));
                GraphEdge ge = e.getEdge();
                // Connected routes should only forward if not absorbed by interface
                GraphEdge other = getGraph().getOtherEnd().get(ge);
                BoolExpr connectedWillSend;
                if (other == null || getGraph().isHost(ge.getPeer())) {
                    Ip ip = ge.getStart().getAddress().getIp();
                    BitVecExpr val = getCtx().mkBV(ip.asLong(), 32);
                    connectedWillSend = mkNot(mkEq(_symbolicPacket.getDstIp(), val));
                } else {
                    Ip ip = other.getStart().getAddress().getIp();
                    BitVecExpr val = getCtx().mkBV(ip.asLong(), 32);
                    connectedWillSend = mkEq(_symbolicPacket.getDstIp(), val);
                }
                BoolExpr canSend = (proto.isConnected() ? connectedWillSend : mkTrue());
                BoolExpr sends = mkAnd(canSend, isBest);
                BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge);
                assert (cForward != null);
                add(mkImplies(sends, cForward));
                // record the negation as well
                cfExprs.merge(ge, sends, (a, b) -> mkOr(a, b));
            }
        }
        // For edges that are never used, we constraint them to not be forwarded out of
        for (GraphEdge ge : getGraph().getEdgeMap().get(router)) {
            if (!constrained.contains(ge)) {
                BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge);
                assert (cForward != null);
                add(mkNot(cForward));
            }
        }
        // Handle the case that the router has no protocol running
        if (!someEdge) {
            for (GraphEdge ge : getGraph().getEdgeMap().get(router)) {
                BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge);
                assert (cForward != null);
                add(mkNot(cForward));
            }
        } else {
            // If no best route, then no forwarding
            Map<Protocol, List<ArrayList<LogicalEdge>>> map = _logicalGraph.getLogicalEdges().get(router);
            Set<GraphEdge> seen = new HashSet<>();
            for (List<ArrayList<LogicalEdge>> eList : map.values()) {
                for (ArrayList<LogicalEdge> edges : eList) {
                    for (LogicalEdge le : edges) {
                        GraphEdge ge = le.getEdge();
                        if (seen.contains(ge)) {
                            continue;
                        }
                        seen.add(ge);
                        BoolExpr expr = cfExprs.get(ge);
                        BoolExpr cForward = _symbolicDecisions.getControlForwarding().get(router, ge);
                        assert (cForward != null);
                        if (expr != null) {
                            add(mkImplies(mkNot(expr), mkNot(cForward)));
                        } else {
                            add(mkNot(cForward));
                        }
                    }
                }
            }
        }
    }
}
Also used : BoolExpr(com.microsoft.z3.BoolExpr) Configuration(org.batfish.datamodel.Configuration) HashMap(java.util.HashMap) Ip(org.batfish.datamodel.Ip) ArrayList(java.util.ArrayList) BitVecExpr(com.microsoft.z3.BitVecExpr) IpAccessList(org.batfish.datamodel.IpAccessList) ArrayList(java.util.ArrayList) List(java.util.List) IpProtocol(org.batfish.datamodel.IpProtocol) RoutingProtocol(org.batfish.datamodel.RoutingProtocol) Protocol(org.batfish.symbolic.Protocol) MatchProtocol(org.batfish.datamodel.routing_policy.expr.MatchProtocol) GraphEdge(org.batfish.symbolic.GraphEdge) HashSet(java.util.HashSet)

Example 20 with Expr

use of com.microsoft.z3.Expr in project batfish by batfish.

the class PropertyChecker method checkEqualLength.

/*
   * Computes whether a collection of source routers will always have
   * equal path length to destination port(s).
   */
public AnswerElement checkEqualLength(HeaderLocationQuestion q) {
    return checkProperty(q, (enc, srcRouters, destPorts) -> {
        PropertyAdder pa = new PropertyAdder(enc.getMainSlice());
        Map<String, ArithExpr> lenVars = pa.instrumentPathLength(destPorts);
        Map<String, BoolExpr> eqVars = new HashMap<>();
        List<Expr> lens = new ArrayList<>();
        for (String router : srcRouters) {
            lens.add(lenVars.get(router));
        }
        BoolExpr allEqual = PropertyAdder.allEqual(enc.getCtx(), lens);
        enc.add(enc.mkNot(allEqual));
        for (Entry<String, ArithExpr> entry : lenVars.entrySet()) {
            String name = entry.getKey();
            BoolExpr b = srcRouters.contains(name) ? allEqual : enc.mkTrue();
            eqVars.put(name, b);
        }
        return eqVars;
    }, (vp) -> new SmtOneAnswerElement(vp.getResult()));
}
Also used : ArithExpr(com.microsoft.z3.ArithExpr) BoolExpr(com.microsoft.z3.BoolExpr) BoolExpr(com.microsoft.z3.BoolExpr) ArithExpr(com.microsoft.z3.ArithExpr) BitVecExpr(com.microsoft.z3.BitVecExpr) Expr(com.microsoft.z3.Expr) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SmtOneAnswerElement(org.batfish.symbolic.answers.SmtOneAnswerElement)

Aggregations

BoolExpr (com.microsoft.z3.BoolExpr)28 Expr (com.microsoft.z3.Expr)27 Test (org.junit.Test)19 HashMap (java.util.HashMap)12 Status (com.microsoft.z3.Status)11 BitVecExpr (com.microsoft.z3.BitVecExpr)10 ArithExpr (com.microsoft.z3.ArithExpr)8 CommunityVar (org.batfish.symbolic.CommunityVar)6 State (de.bmoth.modelchecker.State)5 Ip (org.batfish.datamodel.Ip)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Map (java.util.Map)4 BatfishException (org.batfish.common.BatfishException)4 Prefix (org.batfish.datamodel.Prefix)4 BooleanExpr (org.batfish.datamodel.routing_policy.expr.BooleanExpr)4 Protocol (org.batfish.symbolic.Protocol)4 HashSet (java.util.HashSet)3 Collectors (java.util.stream.Collectors)3 MatchProtocol (org.batfish.datamodel.routing_policy.expr.MatchProtocol)3